import { randomUUID } from 'node:crypto';
import { generateSpecQuestions, formatQuestionsAsPrompt, parseAnswers, } from '../engine/elicitation/index.js';
import { buildDefaultAnswers } from '../engine/elicitation/non-interactive-defaults.js';
/** Build a clarification summary from parsed answers */
function buildSummary(session, parsedAnswers) {
    const lines = [`## Clarification Summary for "${session.title}"`, ''];
    const labelMap = {
        users: 'Users',
        success: 'Success criteria',
        scope: 'Scope',
        edge_cases: 'Edge cases',
        data: 'Data requirements',
        api_contract: 'API changes',
        performance: 'Performance requirements',
    };
    for (const [key, label] of Object.entries(labelMap)) {
        const answer = parsedAnswers[key];
        if (answer !== undefined && answer.length > 0) {
            lines.push(`**${label}**: ${answer}`);
        }
    }
    lines.push('');
    lines.push('**Ready to create spec!** Call `create_spec` with:');
    lines.push(`- title: "${session.title}"`);
    const answersSummary = Object.entries(parsedAnswers)
        .map(([k, v]) => `${labelMap[k] ?? k}: ${v}`)
        .join('; ');
    const enrichedDescription = answersSummary.length > 0 ? `${session.title}. ${answersSummary}` : session.title;
    lines.push(`- description: "${enrichedDescription}"`);
    return lines.join('\n');
}
/** Handle elicit_requirements tool call */
export function handleElicitRequirements(input) {
    const { title, description, answers, mode } = input;
    // intakeRef is silently acknowledged — used by downstream agents to chain context
    const context = {
        hasDatabase: description.toLowerCase().includes('data') ||
            description.toLowerCase().includes('store') ||
            description.toLowerCase().includes('database'),
        isApi: description.toLowerCase().includes('api') || description.toLowerCase().includes('endpoint'),
    };
    const questions = generateSpecQuestions(title, description, context);
    const sessionId = input.sessionId ?? randomUUID();
    const session = {
        sessionId,
        title,
        questions,
        answers: {},
    };
    // SPEC-724: Non-interactive mode — synthesise defaults without AskUserQuestion round-trip
    if (mode === 'non-interactive' && (answers === undefined || answers.trim().length === 0)) {
        const defaultAnswers = buildDefaultAnswers(input);
        session.answers = defaultAnswers;
        session.completedAt = new Date().toISOString();
        const summary = buildSummary(session, defaultAnswers);
        return Promise.resolve({
            content: [{ type: 'text', text: summary }],
            structuredContent: {
                summary,
                mode: 'non-interactive',
            },
        });
    }
    // First call — return questions
    if (answers === undefined || answers.trim().length === 0) {
        const prompt = formatQuestionsAsPrompt(session);
        const text = [
            `## Questions for "${title}"`,
            '',
            prompt,
            '',
            '**Next step**: Answer these questions, then call `elicit_requirements` again with your answers and the sessionId.',
            `sessionId: ${sessionId}`,
        ].join('\n');
        return Promise.resolve({ content: [{ type: 'text', text }] });
    }
    // Follow-up call — parse answers and return summary
    const parsedAnswers = parseAnswers(questions, answers);
    session.answers = parsedAnswers;
    session.completedAt = new Date().toISOString();
    const summary = buildSummary(session, parsedAnswers);
    return Promise.resolve({ content: [{ type: 'text', text: summary }] });
}
//# sourceMappingURL=elicit-requirements-handler.js.map