// tools/spec-effectiveness-score.ts — MCP tool handler (SPEC-611)
import { specStore } from '../storage/index.js';
import { calculateSpecEffectivenessScore } from '../engine/spec-effectiveness/calculator.js';
import { buildProjectEffectivenessReport } from '../engine/spec-effectiveness/project-report.js';
import { resolveProjectId } from './resolve-project-id.js';
// ── Formatting helpers ───────────────────────────────────────────────────────
function scoreLabel(score) {
    if (score >= 85) {
        return 'Excellent';
    }
    if (score >= 70) {
        return 'Good';
    }
    if (score >= 50) {
        return 'Fair';
    }
    return 'Poor';
}
function formatSingleScore(result) {
    const lines = [];
    lines.push(`# Spec Effectiveness Score — ${result.specId}`);
    lines.push('');
    lines.push(`**Score**: ${result.score}/100 (${scoreLabel(result.score)})`);
    lines.push('');
    lines.push('## Components');
    lines.push('');
    lines.push('| Metric | Value |');
    lines.push('|--------|-------|');
    lines.push(`| Adherence Rate | ${result.components.adherenceRate.toFixed(0)}% |`);
    lines.push(`| First-Pass Success | ${result.components.firstPassSuccess === 100 ? 'Yes' : 'No'} |`);
    lines.push(`| Rework Ratio | ${result.components.reworkRatio.toFixed(0)}% |`);
    lines.push(`| Estimation Accuracy | ${result.components.estimationAccuracy.toFixed(0)}% |`);
    lines.push(`| Drift Penalty | ${result.components.driftPenalty.toFixed(0)}% |`);
    if (result.warnings.length > 0) {
        lines.push('');
        lines.push('## Warnings');
        lines.push('');
        for (const w of result.warnings) {
            lines.push(`- WARNING: ${w}`);
        }
    }
    if (result.suggestions.length > 0) {
        lines.push('');
        lines.push('## Improvement Suggestions');
        lines.push('');
        for (const s of result.suggestions) {
            lines.push(`- ${s}`);
        }
    }
    return lines.join('\n');
}
function formatProjectReport(report) {
    const lines = [];
    lines.push(`# Project Effectiveness Report — ${report.projectId}`);
    lines.push('');
    lines.push(`**Specs analyzed**: ${report.specCount}`);
    lines.push(`**Average score**: ${report.averageScore}/100`);
    lines.push(`**Trend**: ${report.trend}`);
    lines.push('');
    if (report.topSpecs.length > 0) {
        lines.push('## Top Specs');
        lines.push('');
        for (const s of report.topSpecs) {
            lines.push(`- ${s.specId} — ${s.title}: ${s.score}/100`);
        }
        lines.push('');
    }
    if (report.bottomSpecs.length > 0) {
        lines.push('## Specs Needing Improvement');
        lines.push('');
        for (const s of report.bottomSpecs) {
            lines.push(`- ${s.specId} — ${s.title}: ${s.score}/100`);
        }
        lines.push('');
    }
    if (report.patterns.length > 0) {
        lines.push('## Patterns Identified');
        lines.push('');
        for (const p of report.patterns) {
            lines.push(`### ${p.type} (${p.count} spec${p.count !== 1 ? 's' : ''})`);
            lines.push(p.recommendation);
            lines.push('');
        }
    }
    return lines.join('\n');
}
// ── Handler ──────────────────────────────────────────────────────────────────
export async function handleSpecEffectivenessScore(args) {
    const projectId = resolveProjectId(args);
    if (!projectId) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Provide projectId or projectPath to identify the project.',
                },
            ],
            isError: true,
        };
    }
    // ── Per-spec mode ──────────────────────────────────────────────────────────
    if (args.specId !== undefined && args.specId.trim() !== '') {
        const spec = await specStore.getSpec(projectId, args.specId);
        if (!spec) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `Spec '${args.specId}' not found in project '${projectId}'.`,
                    },
                ],
                isError: true,
            };
        }
        const result = calculateSpecEffectivenessScore(spec);
        const formatted = formatSingleScore(result);
        return {
            content: [{ type: 'text', text: formatted }],
            structuredContent: result,
        };
    }
    // ── Aggregate mode ─────────────────────────────────────────────────────────
    const specs = await specStore.listSpecs(projectId);
    const doneSpecs = specs.filter((s) => s.status === 'done');
    if (doneSpecs.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'No completed specs found in this project. Transition at least one spec to `done` with actuals recorded to generate an effectiveness report.',
                },
            ],
        };
    }
    const report = buildProjectEffectivenessReport(projectId, doneSpecs);
    const formatted = formatProjectReport(report);
    return {
        content: [{ type: 'text', text: formatted }],
        structuredContent: report,
    };
}
//# sourceMappingURL=spec-effectiveness-score.js.map