/**
 * Unified agent routing: regex (instant) → optional Balanced 4B → V3 execution hints.
 */
import { inferAgentTaskType, isTrivialHtmlPageRequest, isAgentContinuePrompt, isAgentRetryPrompt, hasGameIntent, hasWebPageIntent, taskRequiresWorkspaceChanges, stripExecutionShaping, } from './requestIntent.js';
import { isFastInferenceRouterAvailable, routeWithBalanced4b, shouldUseBalancedRouter, } from './fastAgentRouter.js';
function forceTemplateScaffold() {
    const v = String(process.env.VIGTHORIA_FORCE_TEMPLATE_SCAFFOLD || '').trim().toLowerCase();
    return v === '1' || v === 'true' || v === 'yes';
}
function wantsInstantTemplatePath(prompt) {
    return /instant[- ]template|template[- ]instant|use the instant-template path/i.test(prompt);
}
function normalizeTaskKind(value, fallback) {
    const kind = String(value || fallback).trim().toLowerCase();
    const allowed = new Set([
        'web-build', 'game-build', 'implementation', 'analysis', 'debugging', 'verification', 'build', 'repair',
    ]);
    if (allowed.has(kind)) {
        return kind === 'build' ? 'implementation' : kind;
    }
    return fallback;
}
function mergeLlmRoute(regexTask, prompt, parsed) {
    const llmPath = String(parsed.path || '').toLowerCase();
    const llmTask = normalizeTaskKind(parsed.task_kind || parsed.taskKind, regexTask);
    const llmFast = parsed.fast_path ?? parsed.fastPath ?? undefined;
    const confidence = Number(parsed.confidence) || 0.75;
    const reason = String(parsed.reason || 'balanced-4b router');
    // Regex game/web signals override wrong LLM labels (hello-world → v3-agent bug).
    if (isTrivialHtmlPageRequest(prompt) || (hasWebPageIntent(prompt) && !hasGameIntent(prompt) && llmTask === 'game-build')) {
        return {
            path: 'template-instant',
            taskKind: 'web-build',
            fastPath: 'template-instant',
            confidence: Math.max(confidence, 0.92),
            reason: 'regex web-page override',
            source: 'merged',
        };
    }
    if (llmPath === 'template-instant' || llmPath === 'html-template' || llmFast === 'template-instant') {
        if (hasWebPageIntent(prompt) || isTrivialHtmlPageRequest(prompt)) {
            return {
                path: 'template-instant',
                taskKind: 'web-build',
                fastPath: 'template-instant',
                confidence,
                reason,
                source: 'merged',
            };
        }
    }
    if (llmPath === 'analysis-only' || llmTask === 'analysis' || llmTask === 'debugging') {
        if (!taskRequiresWorkspaceChanges(prompt)) {
            return {
                path: 'analysis-only',
                taskKind: llmTask === 'debugging' ? 'debugging' : 'analysis',
                confidence,
                reason,
                source: 'balanced-4b',
            };
        }
    }
    if (hasGameIntent(prompt) || llmTask === 'game-build') {
        return {
            path: 'v3-agent',
            taskKind: 'game-build',
            confidence,
            reason,
            source: 'merged',
        };
    }
    const taskKind = (regexTask === 'web-build' || regexTask === 'game-build') ? regexTask : (llmTask || regexTask);
    return {
        path: 'v3-agent',
        taskKind,
        fastPath: typeof llmFast === 'string' ? llmFast : undefined,
        confidence,
        reason,
        source: 'balanced-4b',
    };
}
export async function resolveAgentRoute(api, prompt) {
    const stripped = stripExecutionShaping(prompt);
    if (isAgentContinuePrompt(stripped)) {
        const regexTask = inferAgentTaskType(stripped);
        return {
            path: 'v3-agent',
            taskKind: regexTask === 'analysis' ? 'implementation' : regexTask,
            confidence: 0.92,
            reason: 'continue follow-up (regex)',
            source: 'regex',
        };
    }
    if (isAgentRetryPrompt(stripped)) {
        const regexTask = inferAgentTaskType(stripped);
        return {
            path: 'v3-agent',
            taskKind: regexTask === 'analysis' ? 'implementation' : regexTask,
            confidence: 0.92,
            reason: 'retry follow-up (regex)',
            source: 'regex',
        };
    }
    if (isTrivialHtmlPageRequest(stripped)) {
        return {
            path: 'template-instant',
            taskKind: 'web-build',
            fastPath: 'template-instant',
            confidence: 1,
            reason: 'trivial html page (regex)',
            source: 'regex-trivial',
        };
    }
    const regexTask = inferAgentTaskType(stripped);
    if (!taskRequiresWorkspaceChanges(stripped) && (regexTask === 'analysis' || regexTask === 'debugging')) {
        return {
            path: 'analysis-only',
            taskKind: regexTask,
            confidence: 0.95,
            reason: 'read-only analysis (regex)',
            source: 'regex',
        };
    }
    if (hasGameIntent(stripped) && regexTask === 'game-build') {
        if (forceTemplateScaffold() || wantsInstantTemplatePath(stripped)) {
            return {
                path: 'template-instant',
                taskKind: 'game-build',
                fastPath: 'template-instant',
                confidence: 0.98,
                reason: 'express game template scaffold',
                source: 'regex',
            };
        }
        return {
            path: 'v3-agent',
            taskKind: 'game-build',
            confidence: 0.95,
            reason: 'game build (regex)',
            source: 'regex',
        };
    }
    const selfHosted = api.getSelfHostedModelsApiUrl();
    const tryLlm = shouldUseBalancedRouter(stripped, regexTask)
        && await isFastInferenceRouterAvailable(selfHosted);
    if (tryLlm) {
        const llm = await routeWithBalanced4b(stripped, selfHosted);
        if (llm.ok && llm.parsed) {
            const merged = mergeLlmRoute(regexTask, stripped, llm.parsed);
            return {
                ...merged,
                routerLatencyMs: llm.latencyMs,
                routerModel: llm.model,
            };
        }
    }
    return {
        path: 'v3-agent',
        taskKind: regexTask,
        confidence: 0.8,
        reason: 'default v3 agent (regex)',
        source: 'regex',
    };
}
