// spec-migrator/reconcile-paths.ts — Reconcile specs.json paths with filesystem
import { readdir, access } from 'node:fs/promises';
import { join } from 'node:path';
/**
 * Reconcile specs.json paths with actual filesystem locations.
 * After discoverAndFlattenSpecs() renames/moves folders, specs.json may still
 * reference old paths. This function detects broken paths and fixes them by
 * scanning planu/specs/ for the matching SPEC-XXX folder.
 */
export async function reconcileSpecPaths(projectPath, deps, projectId) {
    const specs = await deps.listSpecs(projectId);
    const specsRoot = join(projectPath, 'planu/specs');
    const errors = [];
    let reconciledCount = 0;
    // Build a map of actual folder names on disk for fast lookup
    let entries;
    try {
        entries = await readdir(specsRoot, { withFileTypes: true });
    }
    catch {
        return { reconciledCount: 0, errors: [] };
    }
    const diskFolders = entries.filter((e) => e.isDirectory()).map((e) => e.name);
    for (const spec of specs) {
        if (!spec.specPath) {
            continue;
        }
        // Check if current specPath exists on disk
        const fullSpecPath = join(projectPath, spec.specPath);
        try {
            await access(fullSpecPath);
            continue; // Path is valid — skip
        }
        catch {
            /* path broken — needs reconciliation */
        }
        // Find the matching folder by SPEC ID prefix (e.g., SPEC-001-)
        const matchingFolder = diskFolders.find((f) => f.startsWith(`${spec.id}-`));
        if (!matchingFolder) {
            continue; // No matching folder found — can't fix
        }
        // Build updated paths
        const newFolder = `planu/specs/${matchingFolder}`;
        const rewrite = (p) => {
            // Replace the entire folder path portion, preserving the filename
            const filename = p.split('/').pop() ?? '';
            return `${newFolder}/${filename}`;
        };
        try {
            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);
            }
            await deps.updateSpec(projectId, spec.id, updates);
            reconciledCount++;
        }
        catch (err) {
            errors.push(`${spec.id}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    return { reconciledCount, errors };
}
//# sourceMappingURL=reconcile-paths.js.map