import { ti } from '../i18n/index.js';
import { knowledgeStore } from '../storage/index.js';
import { randomUUID } from 'node:crypto';
import { isShortTopic, generateMetaQuestions, detectContradictions, buildSuggestedAnswers, } from './clarify-requirements/questions.js';
import { generateQuestions } from './clarify-requirements/questions-context.js';
/** Resume an existing clarification session with new answers. */
async function handleResumeSession(projectId, sessionId, newAnswers, knowledge) {
    const existing = await knowledgeStore.getClarification(projectId, sessionId).catch(() => null);
    if (!existing) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({
                        error: `Session '${sessionId}' not found. Start a new session by calling clarify_requirements without sessionId.`,
                    }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const mergedAnswers = { ...existing.answers, ...newAnswers };
    const contradictions = Object.keys(mergedAnswers).length > 0 ? detectContradictions(mergedAnswers) : [];
    const criticalIds = existing.questions
        .filter((q) => q.importance === 'critical')
        .map((q) => q.id);
    const specReady = criticalIds.every((id) => {
        const ans = mergedAnswers[id];
        return ans !== undefined && ans.trim() !== '';
    });
    const enriched = existing.questions.map((q) => ({
        ...q,
        suggestedAnswers: q.suggestedAnswers ?? buildSuggestedAnswers(q, knowledge),
    }));
    const updated = {
        ...existing,
        questions: enriched,
        answers: mergedAnswers,
        isComplete: specReady,
        contradictions: contradictions.length > 0 ? contradictions : undefined,
        specReady,
    };
    await knowledgeStore.addClarification(projectId, updated);
    const result = {
        sessionId: existing.id,
        topic: existing.topic,
        questionsCount: existing.questions.length,
        questions: enriched.map((q) => ({
            id: q.id,
            question: q.question,
            category: q.category,
            importance: q.importance,
            suggestedAnswers: q.suggestedAnswers,
            answered: mergedAnswers[q.id] !== undefined,
        })),
        specReady,
        answeredCount: Object.keys(mergedAnswers).length,
        ...(contradictions.length > 0
            ? {
                contradictions,
                contradictionWarning: 'Potential contradictions detected — review before creating the spec.',
            }
            : {}),
        instructions: specReady
            ? 'All critical questions answered. Call create_spec with clarificationSessionId.'
            : `${criticalIds.length - criticalIds.filter((id) => mergedAnswers[id]?.trim()).length} critical question(s) remaining.`,
        message: `Session resumed. ${Object.keys(mergedAnswers).length}/${existing.questions.length} answered.`,
    };
    return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
}
export async function handleClarifyRequirements(params) {
    const { projectId, topic, context, maxQuestions = 7, answers, sessionId } = params;
    try {
        // Load project knowledge — proceed with null if project not yet initialized (SPEC-020: criterion 5.1)
        const knowledge = await knowledgeStore.getKnowledge(projectId).catch(() => null);
        // Resume existing session if sessionId provided
        if (sessionId) {
            return await handleResumeSession(projectId, sessionId, answers ?? {}, knowledge);
        }
        // Detect contradictions in provided answers (if any)
        const contradictions = answers && Object.keys(answers).length > 0 ? detectContradictions(answers) : [];
        // If topic is vague (< 10 words), prepend meta-questions
        const metaQuestions = isShortTopic(topic)
            ? generateMetaQuestions()
            : [];
        // Generate main clarification questions (cap total at maxQuestions)
        const mainMaxQ = Math.max(1, maxQuestions - metaQuestions.length);
        const mainQuestions = generateQuestions(topic, context, knowledge, mainMaxQ);
        const questions = [...metaQuestions, ...mainQuestions].slice(0, maxQuestions);
        // Determine if spec is ready (all critical questions have non-empty answers)
        const criticalIds = questions.filter((q) => q.importance === 'critical').map((q) => q.id);
        const specReady = answers !== undefined &&
            criticalIds.every((id) => {
                const ans = answers[id];
                return ans !== undefined && ans.trim() !== '';
            });
        // Create a clarification session
        const session = {
            id: randomUUID().slice(0, 8),
            projectId,
            topic,
            questions,
            answers: answers ?? {},
            isComplete: specReady,
            createdAt: new Date().toISOString(),
            contradictions: contradictions.length > 0 ? contradictions : undefined,
            specReady,
        };
        // Persist the session
        await knowledgeStore.addClarification(projectId, session);
        const result = {
            sessionId: session.id,
            topic,
            questionsCount: questions.length,
            hasMetaQuestions: metaQuestions.length > 0,
            questions: questions.map((q) => ({
                id: q.id,
                question: q.question,
                category: q.category,
                importance: q.importance,
                suggestedAnswer: q.suggestedAnswer,
                /* v8 ignore next 1 */
                suggestedAnswers: q.suggestedAnswers ?? [],
            })),
            specReady,
            instructions: specReady
                ? 'All critical questions answered. Call create_spec with clarificationSessionId to create a precise spec.'
                : 'Answer the questions above, then call create_spec with the gathered context. You can skip nice-to-have questions if the user does not have strong opinions.',
            message: ti('tools.clarify_requirements.success', {
                count: String(questions.length),
                topic,
            }),
        };
        if (contradictions.length > 0) {
            result.contradictions = contradictions;
            result.contradictionWarning =
                'Potential contradictions detected in your answers — please review before creating the spec.';
        }
        return {
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=clarify-requirements.js.map