// Planu — suggest_deletions tool handler (SPEC-482)
import { z } from 'zod';
import { glob } from 'glob';
import { resolve } from 'node:path';
import { scanDeadCode } from '../../engine/delete-first/dead-code-scanner.js';
import { findDuplications } from '../../engine/delete-first/duplication-finder.js';
import { detectOverEngineering } from '../../engine/delete-first/over-engineering-detector.js';
export const SuggestDeletionsInputSchema = {
    projectPath: z.string().describe('Absolute path to the project root to scan.'),
    files: z
        .array(z.string())
        .optional()
        .describe('Optional list of relative glob patterns to restrict the scan. Defaults to src/**/*.ts.'),
    threshold: z
        .enum(['low', 'medium', 'high'])
        .optional()
        .describe('Minimum severity to include in results. Values: low (all), medium, high. Defaults to low.'),
};
const SEVERITY_RANK = { low: 0, medium: 1, high: 2 };
function severityEmoji(s) {
    if (s === 'high') {
        return '🔴';
    }
    if (s === 'medium') {
        return '🟡';
    }
    return '🟢';
}
function formatMarkdown(candidates, filesAnalyzed) {
    if (candidates.length === 0) {
        return `✅ **No deletion candidates found** across ${filesAnalyzed} files.`;
    }
    const byCategory = new Map();
    for (const c of candidates) {
        const list = byCategory.get(c.category) ?? [];
        list.push(c);
        byCategory.set(c.category, list);
    }
    const lines = [
        `## Deletion Candidates (${candidates.length} found, ${filesAnalyzed} files scanned)`,
        '',
        '| Sev | File | Line | Category | Description |',
        '|-----|------|------|----------|-------------|',
    ];
    for (const c of candidates.slice(0, 30)) {
        const fileParts = c.file.replace(/\\/g, '/').split('/');
        const shortFile = fileParts.slice(-2).join('/');
        lines.push(`| ${severityEmoji(c.severity)} | \`${shortFile}\` | ${c.line} | ${c.category} | ${c.description} |`);
    }
    if (candidates.length > 30) {
        lines.push(`\n_...and ${candidates.length - 30} more. Increase threshold to reduce noise._`);
    }
    lines.push('', '**Suggestions:**');
    const shown = new Set();
    for (const c of candidates.slice(0, 10)) {
        if (!shown.has(c.suggestion)) {
            lines.push(`- ${c.suggestion}`);
            shown.add(c.suggestion);
        }
    }
    return lines.join('\n');
}
export async function handleSuggestDeletions(args) {
    const projectPath = resolve(args.projectPath);
    const threshold = args.threshold ?? 'low';
    const thresholdRank = SEVERITY_RANK[threshold];
    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);
    }
    // Deduplicate
    const unique = [...new Set(filePaths)].filter((f) => !f.includes('.test.'));
    const allCandidates = [
        ...scanDeadCode(unique),
        ...findDuplications(unique),
        ...detectOverEngineering(unique),
    ];
    const filtered = allCandidates.filter((c) => SEVERITY_RANK[c.severity] >= thresholdRank);
    // Sort: high first
    filtered.sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || a.file.localeCompare(b.file));
    const text = formatMarkdown(filtered, unique.length);
    return { content: [{ type: 'text', text }] };
}
//# sourceMappingURL=suggest-deletions.js.map