// Planu — simplicity_metric tool handler (SPEC-482)
import { z } from 'zod';
import { glob } from 'glob';
import { resolve } from 'node:path';
import { computeFileSimplicity, scoreToGrade, } from '../../engine/delete-first/metrics/simplicity.js';
export const SimplicityMetricInputSchema = {
    projectPath: z.string().describe('Absolute path to the project root to analyze.'),
    files: z
        .array(z.string())
        .optional()
        .describe('Optional glob patterns (relative) to restrict analysis. Defaults to src/**/*.ts.'),
};
function gradeEmoji(grade) {
    if (grade === 'A') {
        return '🟢';
    }
    if (grade === 'B') {
        return '🟡';
    }
    if (grade === 'C') {
        return '🟠';
    }
    return '🔴';
}
function buildReport(projectPath, filePaths) {
    const files = [];
    for (const fp of filePaths) {
        const m = computeFileSimplicity(fp);
        if (m !== null) {
            files.push(m);
        }
    }
    files.sort((a, b) => a.score - b.score); // worst first
    const overallScore = files.length > 0 ? Math.round(files.reduce((s, f) => s + f.score, 0) / files.length) : 0;
    return {
        projectPath,
        overallScore,
        overallGrade: scoreToGrade(overallScore),
        files,
        filesAnalyzed: filePaths.length,
        generatedAt: new Date().toISOString(),
    };
}
function formatReport(report) {
    const lines = [
        `## Simplicity Metric`,
        `**Overall: ${report.overallScore}/100 ${gradeEmoji(report.overallGrade)} (${report.overallGrade})** — ${report.filesAnalyzed} files analyzed`,
        '',
        '### Most complex files (worst 10)',
        '',
        '| Grade | File | Score | Avg Fn Len | Max Nest | Ternaries | Regexes | Avg Params |',
        '|-------|------|-------|-----------|---------|----------|--------|----------|',
    ];
    const worst = report.files.slice(0, 10);
    for (const f of worst) {
        lines.push(`| ${gradeEmoji(f.grade)} ${f.grade} | \`${f.file}\` | ${f.score} | ${f.avgFunctionLength} | ${f.maxNestingDepth} | ${f.ternaryChainCount} | ${f.regexCount} | ${f.avgParamCount} |`);
    }
    if (report.files.length > 10) {
        const rest = report.files.slice(10);
        const avgRest = Math.round(rest.reduce((s, f) => s + f.score, 0) / rest.length);
        lines.push(`\n_...${rest.length} more files, avg score ${avgRest}._`);
    }
    lines.push('', '**Grading:** A ≥90 · B ≥75 · C ≥60 · D ≥45 · F <45', '**Key drivers:** function length, nesting depth, nested ternaries.');
    return lines.join('\n');
}
export async function handleSimplicityMetric(args) {
    const projectPath = resolve(args.projectPath);
    const patterns = args.files && args.files.length > 0 ? args.files : ['src/**/*.ts'];
    const filePaths = [];
    for (const pattern of patterns) {
        const found = await glob(pattern, { cwd: projectPath, absolute: true });
        filePaths.push(...found);
    }
    const unique = [...new Set(filePaths)].filter((f) => !f.includes('.test.'));
    if (unique.length === 0) {
        return {
            content: [
                { type: 'text', text: '⚠️ No TypeScript files found matching the given patterns.' },
            ],
            isError: true,
        };
    }
    const report = buildReport(projectPath, unique);
    return { content: [{ type: 'text', text: formatReport(report) }] };
}
//# sourceMappingURL=simplicity-metric.js.map