// spec-migrator/prefix-migration.ts — Add SPEC-XXX- prefix to spec folder names
import { rename, access } from 'node:fs/promises';
import { join, dirname } from 'node:path';
const SPEC_ID_PREFIX_RE = /^SPEC-\d{3,}/;
/**
 * Detect specs whose folder name lacks the SPEC-XXX- prefix.
 * E.g., folder is `planu/specs/login-form/` but should be `planu/specs/SPEC-012-login-form/`.
 */
export function filterUnprefixedSpecs(specs) {
    return specs.filter((s) => {
        if (!s.specPath) {
            return false;
        }
        const parts = s.specPath.split('/');
        // The folder is the second-to-last segment (before spec.md)
        const folder = parts[parts.length - 2];
        return folder !== undefined && !SPEC_ID_PREFIX_RE.test(folder);
    });
}
/**
 * Rename spec folders on disk and update storage paths to include the SPEC-XXX- prefix.
 */
export async function migrateSpecFolderNames(projectPath, specs, deps) {
    const errors = [];
    let migratedCount = 0;
    for (const spec of specs) {
        try {
            const oldDir = dirname(join(projectPath, spec.specPath));
            const parentDir = dirname(oldDir);
            const oldFolderName = oldDir.split('/').pop() ?? '';
            const newFolderName = `${spec.id}-${oldFolderName}`;
            const newDir = join(parentDir, newFolderName);
            // Skip if already correct or target exists
            if (oldFolderName.startsWith(spec.id)) {
                continue;
            }
            try {
                await access(newDir);
                continue; // Target already exists — skip
            }
            catch {
                /* target doesn't exist — proceed */
            }
            await rename(oldDir, newDir);
            // Update all path fields in storage
            const rewrite = (p) => p.replace(`/${oldFolderName}/`, `/${newFolderName}/`);
            const updates = { specPath: rewrite(spec.specPath) };
            if (spec.technicalPath) {
                updates.technicalPath = rewrite(spec.technicalPath);
            }
            if (spec.progressPath) {
                updates.progressPath = rewrite(spec.progressPath);
            }
            if (spec.executiveReportPath) {
                updates.executiveReportPath = rewrite(spec.executiveReportPath);
            }
            if (spec.technicalReportPath) {
                updates.technicalReportPath = rewrite(spec.technicalReportPath);
            }
            if (spec.planPath) {
                updates.planPath = rewrite(spec.planPath);
            }
            try {
                await deps.updateSpec(spec.projectId, spec.id, updates);
            }
            catch (err) {
                // Rollback: rename back to original
                try {
                    await rename(newDir, oldDir);
                }
                catch {
                    /* ignore rollback error */
                }
                throw err;
            }
            migratedCount++;
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            errors.push(`${spec.id}: ${msg}`);
        }
    }
    return { migratedCount, errors };
}
//# sourceMappingURL=prefix-migration.js.map