import { ti } from '../i18n/index.js';
import { specStore, knowledgeStore } from '../storage/index.js';
import { generateChecklist } from '../engine/validator.js';
const CATEGORY_WEIGHTS = {
    completeness: 0.25,
    consistency: 0.2,
    feasibility: 0.2,
    security: 0.15,
    'edge-cases': 0.1,
    ux: 0.1,
};
function itemPassed(item) {
    if (item.passed !== undefined) {
        return item.passed ?? null;
    }
    if (item.answer === 'yes') {
        return true;
    }
    if (item.answer === 'no') {
        return false;
    }
    return null;
}
function computeChecklistScore(items) {
    const categories = Object.keys(CATEGORY_WEIGHTS);
    const categoryScores = [];
    for (const category of categories) {
        const catItems = items.filter((i) => i.category === category);
        const weight = CATEGORY_WEIGHTS[category];
        if (catItems.length === 0) {
            categoryScores.push({ category, score: 0, weight, items: [] });
            continue;
        }
        const passed = catItems.filter((i) => itemPassed(i) === true).length;
        const failed = catItems.filter((i) => itemPassed(i) === false).length;
        const decidable = passed + failed;
        const score = decidable > 0 ? Math.round((passed / decidable) * 100) : 50;
        categoryScores.push({ category, score, weight, items: catItems });
    }
    const active = categoryScores.filter((cs) => cs.items.length > 0);
    const totalWeight = active.reduce((s, cs) => s + cs.weight, 0);
    /* v8 ignore next 2 */
    const overall = totalWeight > 0
        ? Math.round(active.reduce((s, cs) => s + cs.score * cs.weight, 0) / totalWeight)
        : 0;
    const autoCheckedCount = items.filter((i) => i.autoChecked).length;
    const manualPendingCount = items.filter((i) => !i.autoChecked && (i.answer === 'pending' || i.passed === null)).length;
    const recommendation = overall >= 80 ? 'approve' : overall >= 60 ? 'review' : 'reject';
    return {
        overall,
        categories: categoryScores,
        autoCheckedCount,
        manualPendingCount,
        recommendation,
    };
}
function enrichItemsPassed(items) {
    return items.map((item) => {
        const derived = itemPassed(item);
        const detail = item.detail !== undefined
            ? item.detail
            : item.autoChecked && item.answer !== 'pending'
                ? item.answer === 'yes'
                    ? 'Auto-check passed'
                    : 'Auto-check failed'
                : null;
        return { ...item, passed: item.passed !== undefined ? item.passed : derived, detail };
    });
}
export async function handleGenerateChecklist(params) {
    const { specId, projectId, focus, experienceLevel = 'expert' } = params;
    try {
        const spec = await specStore.getSpec(projectId, specId);
        if (!spec) {
            return {
                content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
                isError: true,
            };
        }
        const knowledge = await knowledgeStore.getKnowledge(projectId);
        const checklist = generateChecklist(spec, focus ?? []);
        const enrichedItems = enrichItemsPassed([...checklist.items]);
        if (knowledge) {
            const constitution = await knowledgeStore.getConstitution(projectId);
            if (constitution && constitution.principles.length > 0) {
                const strictPrinciples = constitution.principles.filter((p) => p.enforceLevel === 'strict');
                for (const principle of strictPrinciples.slice(0, 3)) {
                    enrichedItems.push({
                        id: `cl-const-${principle.id}`,
                        question: `Does the implementation comply with: "${principle.principle}"?`,
                        category: 'consistency',
                        answer: 'pending',
                        autoChecked: false,
                        passed: null,
                        detail: null,
                    });
                }
            }
            if (knowledge.database !== 'unknown' &&
                (spec.target === 'backend' || spec.target === 'fullstack')) {
                enrichedItems.push({
                    id: 'cl-db-1',
                    question: `Are database migrations reversible for ${knowledge.database}?`,
                    category: 'feasibility',
                    answer: 'pending',
                    autoChecked: false,
                    passed: null,
                    detail: null,
                });
            }
            if (knowledge.testCommand) {
                enrichedItems.push({
                    id: 'cl-test-1',
                    question: `Do tests pass with \`${knowledge.testCommand}\`?`,
                    category: 'completeness',
                    answer: 'pending',
                    autoChecked: false,
                    passed: null,
                    detail: null,
                });
            }
        }
        const passedCount = enrichedItems.filter((i) => i.answer === 'yes').length;
        const totalCount = enrichedItems.length;
        const score = totalCount > 0 ? Math.round((passedCount / totalCount) * 100) : 0;
        const checklistScore = computeChecklistScore(enrichedItems);
        const byCategory = {};
        for (const item of enrichedItems) {
            const cat = item.category;
            const group = (byCategory[cat] ??= []);
            group.push(item);
        }
        const base = {
            specId,
            projectId,
            focus: focus ?? ['all'],
            totalItems: totalCount,
            passedItems: passedCount,
            pendingItems: enrichedItems.filter((i) => i.answer === 'pending').length,
            failedItems: enrichedItems.filter((i) => i.answer === 'no').length,
            score,
            checklistScore,
            checklist: byCategory,
            generatedAt: new Date().toISOString(),
            message: ti('tools.generate_checklist.success', { totalCount: String(totalCount) }),
        };
        if (experienceLevel === 'beginner') {
            const improvable = checklistScore.manualPendingCount + enrichedItems.filter((i) => i.answer === 'no').length;
            const narrative = `Tu spec tiene ${checklistScore.overall}/100 puntos. Hay ${improvable} cosas que mejorar o verificar manualmente.`;
            return {
                content: [{ type: 'text', text: JSON.stringify({ ...base, narrative }, null, 2) }],
            };
        }
        return {
            content: [{ type: 'text', text: JSON.stringify(base, 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=generate-checklist.js.map