import { isLegacyLocation, createPlanuConfig, serializePlanuConfig, } from './planu-config-writer.js';
import { mkdir, rename, readdir, rmdir, access, writeFile, readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
const LEGACY_TO_MODERN_NAMES = {
    'HU.md': 'spec.md',
    'FICHA-TECNICA.md': 'technical.md',
    'PROGRESS.md': 'progress.md',
};
/**
 * Detect specs stored under a legacy location (docs/sdd/specs/).
 * Caller provides the list of specs (from storage layer).
 */
export function filterLegacySpecs(specs) {
    return specs.filter((s) => isLegacyLocation(s.specPath) || isLegacyLocation(s.technicalPath));
}
/**
 * Migrate legacy specs to planu/specs/ with modern file naming.
 * Moves files on disk and calls the provided updateSpec for each migrated spec.
 * Also rewrites planu.json.
 */
export async function migrateSpecs(projectPath, legacySpecs, deps) {
    const errors = [];
    let migratedCount = 0;
    for (const spec of legacySpecs) {
        try {
            await migrateSingleSpec(projectPath, spec, deps);
            migratedCount++;
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            errors.push(`${spec.id}: ${msg}`);
        }
    }
    // Rewrite planu.json with modern config
    const planuConfigPath = join(projectPath, 'planu.json');
    const planuConfig = createPlanuConfig();
    await writeFile(planuConfigPath, serializePlanuConfig(planuConfig), 'utf-8');
    return { migratedCount, errors };
}
async function migrateSingleSpec(projectPath, spec, deps) {
    const oldSpecDir = dirname(join(projectPath, spec.specPath));
    const newRelDir = spec.specPath
        .replace(/docs\/sdd\/specs/, 'planu/specs')
        .replace(/\/[^/]+$/, '');
    const newAbsDir = join(projectPath, newRelDir);
    // Create target directory
    await mkdir(newAbsDir, { recursive: true });
    // Move and rename known files
    const dirEntries = await safeReaddir(oldSpecDir);
    for (const entry of dirEntries) {
        const modernName = LEGACY_TO_MODERN_NAMES[entry] ?? entry;
        const src = join(oldSpecDir, entry);
        const dest = join(newAbsDir, modernName);
        await rename(src, dest);
    }
    // Update spec paths in storage
    const updates = {
        specPath: rewritePath(spec.specPath),
        technicalPath: rewritePath(spec.technicalPath),
    };
    if (spec.progressPath) {
        updates.progressPath = rewritePath(spec.progressPath);
    }
    if (spec.executiveReportPath) {
        updates.executiveReportPath = rewritePath(spec.executiveReportPath);
    }
    if (spec.technicalReportPath) {
        updates.technicalReportPath = rewritePath(spec.technicalReportPath);
    }
    if (spec.planPath) {
        updates.planPath = rewritePath(spec.planPath);
    }
    await deps.updateSpec(spec.projectId, spec.id, updates);
    // Cleanup empty legacy directories
    await cleanupEmptyDirs(oldSpecDir);
}
function rewritePath(path) {
    return path
        .replace(/docs\/sdd\/specs/, 'planu/specs')
        .replace(/\/HU\.md$/, '/spec.md')
        .replace(/\/FICHA-TECNICA\.md$/, '/technical.md')
        .replace(/\/PROGRESS\.md$/, '/progress.md');
}
async function safeReaddir(dir) {
    try {
        return await readdir(dir);
    }
    catch {
        return [];
    }
}
async function cleanupEmptyDirs(dir) {
    try {
        const entries = await readdir(dir);
        if (entries.length === 0) {
            await rmdir(dir);
            // Try to clean parent too (e.g., docs/sdd/specs/ itself)
            await cleanupEmptyDirs(dirname(dir));
        }
    }
    catch {
        // Directory might not exist or not be empty — safe to ignore
    }
}
/**
 * Check if a project path has a planu.json with legacy specLocation.
 */
export async function hasLegacyConfig(projectPath) {
    try {
        await access(join(projectPath, 'planu.json'));
        const content = await readFile(join(projectPath, 'planu.json'), 'utf-8');
        const config = JSON.parse(content);
        return config.specLocation ? isLegacyLocation(config.specLocation) : false;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=spec-migrator.js.map