/**
 * Shared prompt intent detection for CLI routing, V3 hints, and rescue gating.
 * Keep aligned with V3-Code-Agent/agent.py _classify_request heuristics.
 */
const CLI_SHAPING_BLOCK = /(?:^|\n\n)Platform:\s*(?:Windows|macOS|Linux)\.[\s\S]*?(?=\n\n[A-Z][^\n]{0,40}:|\s*$)/i;
const READONLY_SHAPING_BLOCK = /(?:^|\n\n)(?:Read-only analysis mode is active\.|Diagnostic mode is active\.)[\s\S]*?(?=\n\n[A-Z][^\n]{0,40}:|\s*$)/i;
const BUILD_VERBS = /\b(build|create|make|implement|complete|fix|repair|edit|modify|write|generate|add|finish|scaffold|develop|update|change|refactor|let's|let us|we need|we should|erstelle|erstellen|schreib|schreibe|bearbeite)\b/i;
const ARTIFACT_NOUNS = /\b(file|files|project|game|spiel|app|website|html5|frontend|component|feature|code|workspace|repo|clone|replica|remake|page|site|canvas|sprite|level|levels|enemy|enemies|character|npc|world|scene|script|module|api|database|config|landing|dashboard|platformer|arcade|playable|collectible|scoreboard|leaderboard|pitfall|pacman|rogue|html|css|javascript|typescript)\b/i;
/** Canvas/playable games only — bare "html5" or "website" must NOT match. */
const GAME_INTENT = /\b(game|spiel|playable|html5\s+(?:game|canvas)|html5\s+game|canvas\s+game|game\s+canvas|arcade|platformer|side[- ]?scroller|pitfall|pac[- ]?man|tetris|snake|breakout|pong|roguelike|metroidvania|tower\s+defense|clone\s+of\s+(?:a\s+)?(?:game|pitfall|pac|mario|zelda|arcade)|gameplay|collectible|boss\s+fight|level\s+design|sprite\s+sheet|wild\s+(?:boar|pig|forest)|forest\s+pig)\b/i;
const WEB_PAGE_INTENT = /\b(website|web\s*site|webpage|web\s*page|landing\s+page|home\s*page|index\.html|html\s+page|static\s+page|single\s+page|popup|alert|modal|hello\s+world)\b/i;
const CLONE_BUILD = /\bclone\s+of\b|\b(build|create|make)\s+(?:a|an|the|us|me)?\s*(?:clone|replica|remake|port)\b/i;
const READ_ONLY_INTENT = /\b(analy[sz]e|analyse|analysis|audit|review|inspect|proof|understand|summari[sz]e|scan|read[\s-]?only|where we left|what is|how does|show me|tell me|identify\s+gaps?|gap\s+analysis|production\s+blockers?)\b/i;
const EXPLICIT_WRITE_VERBS = /\b(implement|write|edit|modify|update|fix|repair|create|build|generate|scaffold|deploy|refactor|develop|integrate)\b/i;
const TRIVIAL_HTML_PAGE = /\b(hello\s*world|simple\s+(?:html|web|page|site)|html5\s+website|html\s+5\s+website|popup|alert\s*\(|show\s+a\s+popup|one\s+page|single\s+html)\b/i;
/** Strip CLI-appended platform / mode shaping so it cannot flip quality profiles. */
export function stripExecutionShaping(prompt) {
    return String(prompt || '')
        .replace(CLI_SHAPING_BLOCK, '')
        .replace(READONLY_SHAPING_BLOCK, '')
        .trim();
}
export function hasBuildVerb(prompt) {
    return BUILD_VERBS.test(stripExecutionShaping(prompt));
}
export function hasArtifactNoun(prompt) {
    return ARTIFACT_NOUNS.test(stripExecutionShaping(prompt));
}
/** Game clones require a game target — generic "clone of X" must not imply game-build. */
const GAME_CLONE_TARGET = /\bclone\s+of\s+(?:a\s+)?(?:the\s+)?(?:game|pitfall|pac[- ]?man|mario|zelda|tetris|snake|arcade|spiel)\b/i;
export function hasGameIntent(prompt) {
    const text = stripExecutionShaping(prompt);
    if (GAME_INTENT.test(text)) {
        return true;
    }
    if (GAME_CLONE_TARGET.test(text)) {
        return true;
    }
    if (CLONE_BUILD.test(text) && /\b(game|spiel|pitfall|pacman|arcade|platformer|playable|canvas)\b/i.test(text)) {
        return true;
    }
    return false;
}
export function isContinueOrRetryPrompt(prompt) {
    const text = stripExecutionShaping(prompt).toLowerCase();
    return /\b(continue\s+(?:the\s+)?(?:previous|last|current)\s+(?:agent\s+)?run|\/retry|\/continue|resume\s+(?:the\s+)?(?:failed|unfinished)|planner\s+produced\s+\d+\s+execution\s+tasks)\b/i.test(text);
}
export function hasWebPageIntent(prompt) {
    const text = stripExecutionShaping(prompt);
    return WEB_PAGE_INTENT.test(text) || /\bhtml5\s+website\b/i.test(text);
}
export function isTrivialHtmlPageRequest(prompt) {
    const text = stripExecutionShaping(prompt);
    if (isContinueOrRetryPrompt(prompt)) {
        return false;
    }
    if (!hasBuildVerb(prompt) && !/\b(write|create|make|show)\b/i.test(text)) {
        return false;
    }
    if (hasGameIntent(prompt)) {
        return false;
    }
    if (text.length > 420) {
        return false;
    }
    if (/\b(multi[- ]?page|full\s+saas|dashboard|e[\s-]?commerce|auth|database|backend|api|microservice)\b/i.test(text)) {
        return false;
    }
    return TRIVIAL_HTML_PAGE.test(text)
        || (hasWebPageIntent(prompt) && /\b(html5|html5\s+website|website|popup|hello\s*world)\b/i.test(text));
}
export function hasCloneBuildIntent(prompt) {
    return CLONE_BUILD.test(stripExecutionShaping(prompt)) && hasBuildVerb(prompt);
}
export function hasExplicitWriteIntent(prompt) {
    const text = stripExecutionShaping(prompt);
    return (BUILD_VERBS.test(text) && ARTIFACT_NOUNS.test(text))
        || hasCloneBuildIntent(prompt)
        || (BUILD_VERBS.test(text) && hasGameIntent(prompt));
}
export function taskRequiresWorkspaceChanges(prompt) {
    const text = String(prompt || '').trim();
    const shaped = stripExecutionShaping(text);
    const readOnlyIntent = READ_ONLY_INTENT.test(shaped);
    const explicitWriteIntent = hasExplicitWriteIntent(text);
    if (readOnlyIntent && !explicitWriteIntent) {
        return false;
    }
    return explicitWriteIntent;
}
export function hasAnalyzeAndBuildIntent(prompt) {
    const text = stripExecutionShaping(prompt);
    return /\b(analy[sz]e|analyse)\b/i.test(text)
        && /\b(complete|finish|fix|implement|build|repair|missing\s+elements?)\b/i.test(text)
        && hasExplicitWriteIntent(prompt);
}
export function inferAgentTaskType(prompt) {
    const text = stripExecutionShaping(prompt);
    if (hasAnalyzeAndBuildIntent(prompt)) {
        if (hasGameIntent(prompt)) {
            return 'game-build';
        }
        if (hasWebPageIntent(prompt)) {
            return 'web-build';
        }
        return 'implementation';
    }
    if (/\b(inspect|analyze|analyse|audit|review|find|diagnose|debug|trace|compare|diff|check|investigate)\b/i.test(text)
        && !hasExplicitWriteIntent(prompt)) {
        return 'debugging';
    }
    if (/\b(analy[sz]e|analyse|audit|review|inspect|identify\s+gaps?|gap\s+analysis|production\s+blockers?|read[\s-]?only)\b/i.test(text)
        && !hasExplicitWriteIntent(prompt)) {
        return 'analysis';
    }
    if (hasBuildVerb(prompt) && !/\b(analy[sz]e|analyse|audit|review|inspect)\b/i.test(text)) {
        if (hasGameIntent(prompt)) {
            return 'game-build';
        }
        if (hasWebPageIntent(prompt)) {
            return 'web-build';
        }
        return 'implementation';
    }
    return 'analysis';
}
export function shouldSkipAnalysisRescue(liveOutcome) {
    if (liveOutcome.requiresWorkspaceChanges) {
        return true;
    }
    if ((liveOutcome.tasksTotal || 0) > 0) {
        return true;
    }
    if ((liveOutcome.changedFileCount || 0) > 0) {
        return true;
    }
    return false;
}
export function isPlannerBuildTask(agentTaskType, prompt) {
    const kind = String(agentTaskType || '').toLowerCase();
    if (isTrivialHtmlPageRequest(prompt)) {
        return false;
    }
    if (/^(game-build|web-build|implementation|build|repair|refactor-build)$/.test(kind)) {
        return true;
    }
    return hasExplicitWriteIntent(prompt) && !READ_ONLY_INTENT.test(stripExecutionShaping(prompt));
}
export function resolvePlannerAgentTimeoutMs(baseTimeoutMs, agentTaskType, prompt) {
    if (!isPlannerBuildTask(agentTaskType, prompt)) {
        return baseTimeoutMs;
    }
    const raw = process.env.VIGTHORIA_AGENT_PLANNER_TIMEOUT_MS || process.env.V3_AGENT_PLANNER_TIMEOUT_MS || '900000';
    const extended = Number.parseInt(raw, 10);
    const floor = Number.isFinite(extended) && extended > 0 ? extended : 900000;
    return Math.max(baseTimeoutMs, floor);
}
/** V3 workflow mode: suppress write path when the user did not ask for file changes. */
export function resolveWorkflowType(agentTaskType, prompt) {
    if (hasAnalyzeAndBuildIntent(prompt)) {
        return 'full';
    }
    if (!taskRequiresWorkspaceChanges(prompt)) {
        return 'analysis_only';
    }
    const kind = String(agentTaskType || '').toLowerCase();
    if (kind === 'analysis' || kind === 'debugging' || kind === 'verification') {
        return 'analysis_only';
    }
    return 'full';
}
export function buildExecutionHints(agentTaskType, prompt, options = {}) {
    const workflowType = resolveWorkflowType(agentTaskType, prompt);
    const kind = String(agentTaskType || 'general').toLowerCase();
    const hints = {
        task_kind: kind,
        requires_file_changes: workflowType === 'analysis_only' ? false : undefined,
        classify_from: String(prompt || ''),
        workflow_type: workflowType,
    };
    if (options.fastPath) {
        hints.fast_path = options.fastPath;
    }
    else if (isTrivialHtmlPageRequest(prompt)) {
        hints.fast_path = 'template-instant';
    }
    return hints;
}
