import { scoreAmbiguity, shouldBlock } from '../engine/ambiguity-detector.js';
import { setFocus, getFocus, checkFocusDrift, parseChangeFocusDirective, } from '../engine/focus-tracker.js';
import { getParadigmRecommendations, formatParadigmObservations, } from '../engine/paradigm-advisor.js';
// ---------------------------------------------------------------------------
// Scenario detection
// ---------------------------------------------------------------------------
function detectScenario(description) {
    const lower = description.toLowerCase();
    // Concrete problem indicators — check before existing_project to avoid
    // false positives with phrases like "existing spec"
    if (lower.includes('how to') ||
        lower.includes('how do i') ||
        lower.includes('what tool') ||
        lower.includes('i need help with') ||
        lower.includes('fix') ||
        lower.includes('error') ||
        lower.includes('problem')) {
        return 'concrete_problem';
    }
    // Existing project indicators
    if (lower.includes('already have') ||
        lower.includes('my project') ||
        lower.includes('our project') ||
        /existing project/i.test(description) ||
        lower.includes('/') // path-like input
    ) {
        return 'existing_project';
    }
    return 'new_project';
}
// ---------------------------------------------------------------------------
// Step questions for new_project scenario
// ---------------------------------------------------------------------------
const NEW_PROJECT_STEPS = [
    'What is the main purpose of your app? What problem does it solve and for whom?',
    'What platform will it run on? (web app, mobile iOS/Android, REST API, desktop app, CLI tool)',
    'Do you have a preferred tech stack? (language, framework, database — skip if unsure)',
];
function buildNewProjectResponse(step, collectedInfo) {
    if (step < NEW_PROJECT_STEPS.length) {
        const question = NEW_PROJECT_STEPS[step] ?? NEW_PROJECT_STEPS[0];
        const intro = step === 0
            ? "Welcome to Planu! I'll guide you with a few questions to generate a precise spec.\n\n"
            : `Got it! ${Object.values(collectedInfo).join(', ')}\n\n`;
        return `${intro}Step ${step + 1}/3: ${question}`;
    }
    // All 3 steps complete — suggest create_spec
    const info = Object.values(collectedInfo).join(' | ');
    return (`Great — I have enough context to generate your spec.\n\n` +
        `Summary: ${info}\n\n` +
        `Next step: Call \`create_spec\` with this description:\n` +
        `"${Object.values(collectedInfo).join('. ')}."\n\n` +
        `Or call \`clarify_requirements\` first for deeper requirement analysis.`);
}
// ---------------------------------------------------------------------------
// Existing project scenario
// ---------------------------------------------------------------------------
function buildExistingProjectResponse(description) {
    return (`I'll run a diagnostic on your project.\n\n` +
        `Please provide the project path and call:\n` +
        `- \`init_project\` with your project path (if not yet initialized)\n` +
        `- \`reverse_engineer\` to analyze the codebase\n` +
        `- \`audit\` to check spec health\n\n` +
        `Request received: "${description.slice(0, 120)}"`);
}
// ---------------------------------------------------------------------------
// Concrete problem scenario
// ---------------------------------------------------------------------------
const PROBLEM_TO_TOOL = [
    [/spec|user stor/i, 'create_spec', 'create a spec/user story'],
    [/estimat/i, 'estimate', 'estimate effort and cost'],
    [/test/i, 'generate_tests', 'generate tests'],
    [/document|doc/i, 'generate_docs', 'generate documentation'],
    [/drift|diverge/i, 'detect_drift', 'detect spec drift'],
    [/validat/i, 'validate', 'validate a spec'],
    [/schema|database|db/i, 'design_schema', 'design a database schema'],
    [/ui|interface|screen/i, 'define_ui_contract', 'define a UI contract'],
    [/execution|plan|roadmap/i, 'generate_execution_plan', 'generate an execution plan'],
    [/checklist/i, 'generate_checklist', 'generate a checklist'],
];
function buildConcreteProblemResponse(description) {
    const match = PROBLEM_TO_TOOL.find(([re]) => re.test(description));
    if (match) {
        const [, tool, action] = match;
        return (`It sounds like you want to ${action}.\n\n` +
            `Recommended tool: \`${tool}\`\n\n` +
            `Call \`${tool}\` with your project ID and the relevant parameters.`);
    }
    return (`I can help with that! Here are the most relevant Planu tools:\n\n` +
        `- \`create_spec\` — write a new user story / spec\n` +
        `- \`clarify_requirements\` — clarify vague requirements\n` +
        `- \`estimate\` — estimate effort and cost\n` +
        `- \`validate\` — check if a spec is complete\n` +
        `- \`generate_tests\` — generate test scaffolds\n\n` +
        `What specifically would you like to do?`);
}
// ---------------------------------------------------------------------------
// Paradigm observations (SPEC-035b)
// ---------------------------------------------------------------------------
/**
 * Builds paradigm expert voice observations from a pre-computed ParadigmReport.
 * Degrades gracefully when no detection data is available.
 */
export function buildParadigmObservations(paradigmReport) {
    if (!paradigmReport) {
        return '';
    }
    const recommendations = getParadigmRecommendations(paradigmReport);
    return formatParadigmObservations(recommendations, null);
}
// ---------------------------------------------------------------------------
// Expert observations generator
// ---------------------------------------------------------------------------
function generateExpertObservations(description) {
    const observations = [];
    const lower = description.toLowerCase();
    if (/fast|quick|instant|real.?time/i.test(description)) {
        observations.push({
            type: 'metric',
            text: 'Vague performance requirement detected ("fast", "quick"). Consider specifying concrete SLOs.',
            action: 'Add: "Response time < 200ms at p95 under 1000 concurrent users"',
        });
    }
    if (/payment|stripe|credit card|billing/i.test(description)) {
        observations.push({
            type: 'risk',
            text: 'Payment handling requires PCI-DSS compliance consideration.',
            action: 'Use a certified payment processor (Stripe, Braintree) — never store raw card data.',
        });
    }
    if (/auth|login|password|jwt/i.test(description) && !lower.includes('oauth')) {
        observations.push({
            type: 'suggestion',
            text: 'Consider OAuth2/OIDC instead of custom auth to reduce security risk.',
            action: 'Evaluate Auth0, Clerk, or Supabase Auth before building from scratch.',
        });
    }
    if (/microservice/i.test(description)) {
        observations.push({
            type: 'risk',
            text: 'Microservices add operational complexity. Ensure you need them before committing.',
            action: 'Start with a modular monolith and extract services when load justifies it.',
        });
    }
    return observations;
}
// ---------------------------------------------------------------------------
// Main handler
// ---------------------------------------------------------------------------
export function handleFacilitate(params) {
    const { description, projectId, sessionId, scenario: explicitScenario, collectedInfo = {}, step = 0, targetTool, checkFocus = false, changeFocus, paradigmReport, } = params;
    const sessionKey = sessionId ?? projectId ?? 'default';
    try {
        // --- Focus change directive ---
        const changeFocusText = changeFocus ?? parseChangeFocusDirective(description);
        if (changeFocusText) {
            const newFocus = {
                objective: changeFocusText,
                associatedTool: targetTool,
                startedAt: new Date().toISOString(),
            };
            setFocus(sessionKey, newFocus);
            return ok({
                action: 'focus_updated',
                objective: changeFocusText,
                message: `Focus updated to: "${changeFocusText}". All subsequent requests will be evaluated against this objective.`,
            });
        }
        // --- Focus drift check ---
        if (checkFocus) {
            const shift = checkFocusDrift(sessionKey, description, targetTool);
            if (shift) {
                return ok({
                    action: 'focus_drift_detected',
                    shift,
                    message: shift.redirectMessage,
                    allowProceed: true,
                });
            }
            return ok({
                action: 'focus_aligned',
                currentFocus: getFocus(sessionKey),
                message: 'Request is aligned with the current session focus.',
            });
        }
        // --- Ambiguity check for a specific tool ---
        if (targetTool) {
            const ambiguity = scoreAmbiguity(description);
            const blocked = shouldBlock(targetTool, ambiguity);
            if (blocked) {
                return ok({
                    action: 'ambiguity_block',
                    level: ambiguity.level,
                    score: ambiguity.score,
                    blockingDimension: ambiguity.blockingDimension,
                    question: ambiguity.clarificationQuestion,
                    message: `Before calling \`${targetTool}\`, please answer: ${ambiguity.clarificationQuestion}`,
                });
            }
            return ok({
                action: 'ambiguity_clear',
                level: ambiguity.level,
                score: ambiguity.score,
                message: `Request is clear enough for \`${targetTool}\`. Proceed.`,
            });
        }
        // --- Main facilitate flow ---
        const scenario = explicitScenario ?? detectScenario(description);
        // Set initial focus for new sessions
        const existingFocus = getFocus(sessionKey);
        if (!existingFocus) {
            setFocus(sessionKey, {
                objective: description,
                startedAt: new Date().toISOString(),
            });
        }
        // Generate expert observations (non-blocking)
        const observations = generateExpertObservations(description);
        let guidance;
        switch (scenario) {
            case 'new_project': {
                // Merge current description into collectedInfo for current step
                const updatedInfo = step === 0
                    ? { ...collectedInfo, step0: description }
                    : { ...collectedInfo, [`step${step}`]: description };
                guidance = buildNewProjectResponse(step, updatedInfo);
                break;
            }
            case 'existing_project':
                guidance = buildExistingProjectResponse(description);
                break;
            case 'concrete_problem':
                guidance = buildConcreteProblemResponse(description);
                break;
        }
        const result = {
            action: 'facilitate',
            scenario,
            step,
            guidance,
        };
        if (observations.length > 0) {
            result.expertObservations = observations;
            result.expertNote = 'Expert observations added below — these do not block execution.';
        }
        // SPEC-035b: Append paradigm expert voice observations when detection data is available
        const paradigmObservations = buildParadigmObservations(paradigmReport);
        if (paradigmObservations) {
            result.paradigmObservations = paradigmObservations;
        }
        return ok(result);
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: JSON.stringify({ error: message }, null, 2) }],
            isError: true,
        };
    }
}
function ok(data) {
    return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
}
//# sourceMappingURL=facilitate.js.map