// spec-migrator/filesystem-import.ts — Import specs from disk into the store
import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { parseFrontmatterLocal, validSpecType, validSpecScope, validSpecStatus, validRiskLevel, validSpecTarget, validDifficulty, } from './frontmatter-parser.js';
const SPEC_FOLDER_ID_RE = /^(SPEC-\d{3,})/;
function buildSpecFromMetadata(specId, entryName, projectId, metadata) {
    const now = new Date().toISOString();
    const folder = `planu/specs/${entryName}`;
    const slug = entryName.replace(/^SPEC-\d{3,}-/, '');
    return {
        id: specId,
        title: typeof metadata.title === 'string' ? metadata.title : specId,
        slug,
        type: validSpecType(metadata.type) ?? 'feature',
        scope: validSpecScope(metadata.scope) ?? 'feature',
        status: validSpecStatus(metadata.status) ?? 'draft',
        difficulty: validDifficulty(metadata.difficulty) ?? 3,
        risk: validRiskLevel(metadata.risk) ?? 'medium',
        target: validSpecTarget(metadata.target) ?? 'backend',
        projectId,
        createdAt: typeof metadata.created === 'string' ? new Date(metadata.created).toISOString() : now,
        updatedAt: now,
        specPath: `${folder}/spec.md`,
        technicalPath: `${folder}/technical.md`,
        progressPath: `${folder}/progress.md`,
        estimation: {
            devHours: 0,
            reviewHours: 0,
            recommendedModel: 'sonnet',
            tokensOpus: 0,
            tokensSonnet: 0,
            apiCostUsd: 0,
            hourlyRate: 0,
            humanCostUsd: 0,
            totalCostUsd: 0,
            tokenOptimization: {
                mode: 'local',
                reasoning: 'imported from filesystem',
                estimatedTokens: 0,
                savings: '',
            },
        },
        actuals: null,
        tags: Array.isArray(metadata.tags) ? metadata.tags : [],
        dependencies: [],
        blockedBy: [],
        gitBranch: `feat/${specId.toLowerCase()}-${slug}`,
        impactAnalysis: null,
    };
}
/**
 * Import specs that exist on disk (planu/specs/) but are missing from the store.
 * Reads frontmatter from each spec.md and creates a minimal Spec record in the store.
 * This ensures list_specs returns ALL specs, not just those created via create_spec.
 */
export async function importFilesystemSpecs(projectPath, deps, projectId) {
    const specsRoot = join(projectPath, 'planu/specs');
    const errors = [];
    let importedCount = 0;
    const storeSpecs = await deps.listSpecs(projectId);
    const storeIds = new Set(storeSpecs.map((s) => s.id));
    let entries;
    try {
        entries = await readdir(specsRoot, { withFileTypes: true });
    }
    catch {
        return { importedCount: 0, errors: [] };
    }
    for (const entry of entries) {
        if (!entry.isDirectory()) {
            continue;
        }
        const idMatch = SPEC_FOLDER_ID_RE.exec(entry.name);
        if (!idMatch?.[1]) {
            continue;
        }
        const specId = idMatch[1];
        if (storeIds.has(specId)) {
            continue;
        }
        const specMdPath = join(specsRoot, entry.name, 'spec.md');
        try {
            const content = await readFile(specMdPath, 'utf-8');
            const { metadata } = parseFrontmatterLocal(content);
            const spec = buildSpecFromMetadata(specId, entry.name, projectId, metadata);
            await deps.createSpec(projectId, spec);
            storeIds.add(specId);
            importedCount++;
        }
        catch (err) {
            errors.push(`${specId}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    return { importedCount, errors };
}
//# sourceMappingURL=filesystem-import.js.map