// tools/repair-spec.ts — MCP handler for the repair_spec tool (SPEC-164)
import { specStore } from '../storage/index.js';
import { repairSpec } from '../engine/spec-repair.js';
import { formatSuccess, formatError } from './response-helpers.js';
import { readFile, writeFile } from 'node:fs/promises';
import { ti } from '../i18n/index.js';
/**
 * Handle the repair_spec tool: auto-detect and fix common spec problems.
 *
 * In dry-run mode (default: false), returns detected issues without writing files.
 * When dryRun=false, applies fixes to spec.md on disk.
 */
export async function handleRepairSpec(args) {
    const { projectId, specId, dryRun = false } = args;
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: formatError(ti('spec.notFound', { id: specId })) }],
            isError: true,
        };
    }
    let specContent;
    try {
        specContent = await readFile(spec.specPath, 'utf-8');
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
            content: [
                {
                    type: 'text',
                    text: formatError(`Could not read spec file at ${spec.specPath}: ${msg}`, 'Verify the file exists and is readable.'),
                },
            ],
            isError: true,
        };
    }
    const result = repairSpec(specContent, dryRun);
    // Persist repaired content when not a dry run and fixes were applied
    if (!dryRun && result.fixCount > 0) {
        try {
            await writeFile(spec.specPath, result.repairedContent, 'utf-8');
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            return {
                content: [
                    {
                        type: 'text',
                        text: formatError(`Fixes detected but could not write repaired spec: ${msg}`, 'Check file permissions and try again.'),
                    },
                ],
                isError: true,
            };
        }
    }
    const mode = dryRun ? 'Dry run' : 'Applied';
    const fixSummary = result.fixes.length === 0
        ? 'No issues detected — spec is well-formed.'
        : result.fixes
            .map((f, i) => `${String(i + 1)}. [${f.type}] ${f.description}${f.line > 0 ? ` (line ${String(f.line)})` : ''}`)
            .join('\n');
    const body = [
        `**Spec:** ${specId}`,
        `**Mode:** ${mode}`,
        `**Issues found:** ${String(result.fixes.length)}`,
        `**Fixes applied:** ${String(result.fixCount)}`,
        '',
        result.fixes.length > 0 ? `### Detected Issues\n${fixSummary}` : fixSummary,
    ].join('\n');
    const title = dryRun
        ? `repair_spec — ${String(result.fixes.length)} issue(s) detected`
        : `repair_spec — ${String(result.fixCount)} fix(es) applied`;
    const nextSteps = result.fixes.length > 0
        ? dryRun
            ? [`Run repair_spec without dryRun=true to apply ${String(result.fixes.length)} fix(es)`]
            : [
                'Review the repaired spec.md and adjust any [REWRITE] placeholders',
                'Run validate to confirm the spec is ready',
            ]
        : ['No action needed — spec is well-formed'];
    return {
        content: [{ type: 'text', text: formatSuccess(title, body, nextSteps) }],
        structuredContent: {
            specId,
            dryRun,
            fixCount: result.fixCount,
            issueCount: result.fixes.length,
            fixes: result.fixes,
        },
    };
}
//# sourceMappingURL=repair-spec.js.map