// Planu — sustainability_score tool handler (SPEC-482)
import { z } from 'zod';
import { glob } from 'glob';
import { resolve } from 'node:path';
import { computeSustainabilityReport } from '../../engine/delete-first/metrics/sustainability.js';
export const SustainabilityScoreInputSchema = {
    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 formatReport(report) {
    const lines = [
        `## Sustainability Score`,
        `**Overall: ${report.overallScore}/100 ${gradeEmoji(report.overallGrade)} (${report.overallGrade})** — ${report.filesAnalyzed} files analyzed`,
        '',
        '### Worst modules (bottom 10)',
        '',
        '| Grade | File | Score | Simplicity | Cohesion | Coupling |',
        '|-------|------|-------|-----------|---------|---------|',
    ];
    const worst = report.modules.slice(0, 10);
    for (const m of worst) {
        lines.push(`| ${gradeEmoji(m.grade)} ${m.grade} | \`${m.file}\` | ${m.score} | ${m.simplicity.toFixed(2)} | ${m.cohesion.toFixed(2)} | ${m.coupling} |`);
    }
    if (report.modules.length > 10) {
        const rest = report.modules.slice(10);
        const avgRest = Math.round(rest.reduce((s, m) => s + m.score, 0) / rest.length);
        lines.push(`\n_...${rest.length} more modules, avg score ${avgRest}._`);
    }
    lines.push('', '**Formula:** `score = simplicity × cohesion / (1 + coupling/10) × 100`', '**Tip:** High coupling is the most impactful driver — reduce fan-in/fan-out to improve score.');
    return lines.join('\n');
}
export async function handleSustainabilityScore(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 = computeSustainabilityReport(projectPath, unique);
    return { content: [{ type: 'text', text: formatReport(report) }] };
}
//# sourceMappingURL=sustainability-score.js.map