// tools/ssr-back-migration.ts — SPEC-752: ssr_back_migration tool handler
import { runSsrBackMigration } from '../engine/spec-migrator/ssr-back-migration.js';
import { resolveProjectIdOrAutoDetect } from './resolve-project-id.js';
export async function handleSsrBackMigration(args) {
    const dryRun = args.dryRun ?? true;
    const foldProgressMd = args.foldProgressMd ?? true;
    // SPEC-1008: default to true so the migrator actually clears legacy artifacts
    // in repos with many done specs. Explicit `allowDoneSpecs: false` preserves
    // the old behavior for callers that need it.
    const allowDoneSpecs = args.allowDoneSpecs ?? true;
    // Resolve project path
    const resolved = await resolveProjectIdOrAutoDetect({
        projectPath: args.projectPath,
    });
    let projectPath = args.projectPath;
    if (!projectPath && resolved.ok) {
        // Try to get the path from knowledge if auto-detected
        const { knowledgeStore } = await import('../storage/index.js');
        const knowledge = await knowledgeStore.getKnowledge(resolved.projectId).catch(() => null);
        projectPath = knowledge?.projectPath ?? args.projectPath;
    }
    if (!projectPath) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'ssr_back_migration: projectPath is required. Pass projectPath or ensure the project is initialized with init_project.',
                },
            ],
        };
    }
    const report = await runSsrBackMigration({
        projectPath,
        dryRun,
        foldProgressMd,
        allowDoneSpecs,
    });
    const mode = dryRun ? '**DRY RUN** — no files changed' : '**EXECUTED** — files mutated';
    const lines = [
        `## SSR Back-Migration Report`,
        ``,
        mode,
        ``,
        `| Metric | Count |`,
        `|--------|-------|`,
        `| Scanned | ${report.scanned} |`,
        `| Migrated | ${report.migrated} |`,
        `| Already unified | ${report.alreadyUnified} |`,
        `| Skipped | ${report.skipped.length} |`,
    ];
    if (report.mutations.length > 0) {
        lines.push('', '### Mutations', '');
        for (const m of report.mutations) {
            const delta = m.byteDelta > 0 ? `+${m.byteDelta}B` : `${m.byteDelta}B`;
            lines.push(`- **${m.specId}**: \`${m.action}\` (${delta})`);
        }
    }
    if (report.skipped.length > 0) {
        lines.push('', '### Skipped', '');
        for (const s of report.skipped) {
            lines.push(`- **${s.specId}**: ${s.reason}`);
        }
    }
    if (dryRun && report.scanned > 0) {
        lines.push('', '> Re-run with `dryRun: false` to apply the migration.');
    }
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
        structuredContent: report,
    };
}
//# sourceMappingURL=ssr-back-migration.js.map