// tools/spec-quality-score-handler.ts — spec_quality_score tool handler (SPEC-314)
import { specStore } from '../storage/index.js';
import { scoreSpecQuality } from '../engine/spec-quality-scorer.js';
import { resolveProjectId, missingProjectIdError } from './resolve-project-id.js';
import { toolResult, errText } from './response-helpers.js';
// ── Formatting ───────────────────────────────────────────────────────────────
function gradeLabel(grade) {
    switch (grade) {
        case 'A':
            return 'Excellent';
        case 'B':
            return 'Good';
        case 'C':
            return 'Fair';
        case 'D':
            return 'Poor';
        case 'F':
            return 'Failing';
    }
}
function scoreBar(score, max) {
    const filled = Math.round((score / max) * 10);
    const empty = 10 - filled;
    return `[${'#'.repeat(filled)}${'.'.repeat(empty)}] ${String(score)}/${String(max)}`;
}
function formatReport(report) {
    const { score, dimensions } = report;
    const lines = [];
    lines.push(`# Quality Score — ${report.specId}`);
    lines.push('');
    lines.push(`**Grade**: ${score.grade} (${gradeLabel(score.grade)}) — ${String(score.total)}/100`);
    lines.push('');
    lines.push('## Score Breakdown');
    lines.push('');
    lines.push(`| Dimension | Score | Bar |`);
    lines.push(`|-----------|-------|-----|`);
    lines.push(`| Completeness | ${String(score.completeness)}/25 | ${scoreBar(score.completeness, 25)} |`);
    lines.push(`| Testability | ${String(score.testability)}/25 | ${scoreBar(score.testability, 25)} |`);
    lines.push(`| Ambiguity | ${String(score.ambiguity)}/25 | ${scoreBar(score.ambiguity, 25)} |`);
    lines.push(`| Risk | ${String(score.risk)}/25 | ${scoreBar(score.risk, 25)} |`);
    lines.push(`| **Total** | **${String(score.total)}/100** | ${scoreBar(score.total, 100)} |`);
    lines.push('');
    // Per-dimension issues
    const dimensionEntries = [
        ['Completeness', dimensions.completeness],
        ['Testability', dimensions.testability],
        ['Ambiguity', dimensions.ambiguity],
        ['Risk', dimensions.risk],
    ];
    const allIssues = [];
    const allRecs = [];
    for (const [name, detail] of dimensionEntries) {
        if (detail.issues.length > 0) {
            lines.push(`## ${name} Issues`);
            lines.push('');
            for (const issue of detail.issues) {
                lines.push(`- ${issue}`);
                allIssues.push(issue);
            }
            lines.push('');
        }
        for (const rec of detail.recommendations) {
            allRecs.push(rec);
        }
    }
    if (allRecs.length > 0) {
        lines.push('## Recommendations');
        lines.push('');
        const deduped = [...new Set(allRecs)];
        for (const rec of deduped) {
            lines.push(`- ${rec}`);
        }
        lines.push('');
    }
    // Grade interpretation
    lines.push('## Grade Interpretation');
    lines.push('');
    lines.push('| Grade | Range | Meaning |');
    lines.push('|-------|-------|---------|');
    lines.push('| A | 90-100 | Ready for implementation |');
    lines.push('| B | 75-89 | Minor improvements recommended |');
    lines.push('| C | 60-74 | Needs work before implementation |');
    lines.push('| D | 45-59 | Significant gaps — do not implement yet |');
    lines.push('| F | 0-44 | Spec requires major revision |');
    return lines.join('\n');
}
// ── Handler ──────────────────────────────────────────────────────────────────
export async function handleSpecQualityScore(args) {
    const projectId = resolveProjectId(args);
    if (!projectId) {
        return missingProjectIdError;
    }
    const { specId } = args;
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return errText(`Spec '${specId}' not found in project '${projectId}'`);
    }
    const report = await scoreSpecQuality(spec);
    const formatted = formatReport(report);
    return toolResult(formatted, {
        specId: report.specId,
        score: report.score,
        dimensions: {
            completeness: {
                score: report.dimensions.completeness.score,
                issues: report.dimensions.completeness.issues,
            },
            testability: {
                score: report.dimensions.testability.score,
                issues: report.dimensions.testability.issues,
            },
            ambiguity: {
                score: report.dimensions.ambiguity.score,
                issues: report.dimensions.ambiguity.issues,
            },
            risk: { score: report.dimensions.risk.score, issues: report.dimensions.risk.issues },
        },
    });
}
//# sourceMappingURL=spec-quality-score-handler.js.map