// engine/spec-format/technical-md-populator.ts — SPEC-586: Parse spec body to populate ## Technical
import { stat } from 'node:fs/promises';
import { join } from 'node:path';
const FILE_PATH_RE = /\b(src|tests)\/[\w/-]+\.[a-z]+\b/g;
function extractPathsFromSection(sectionText) {
    const paths = [];
    const listRe = /^-\s+`?(src\/[\w./-]+|tests\/[\w./-]+)`?/gm;
    let m;
    while ((m = listRe.exec(sectionText)) !== null) {
        const match = m[0]
            .replace(/^-\s+`?/, '')
            .replace(/`.*$/, '')
            .trim();
        if (match) {
            paths.push(match);
        }
    }
    return paths;
}
function parseSectionedFileLists(body) {
    const filesSection = /##\s+Files\s+likely\s+to\s+change[\s\S]*?(?=^##\s|$)/m.exec(body);
    const createSection = /###\s+Create[\s\S]*?(?=###|^##\s|$)/m.exec(filesSection?.[0] ?? body);
    const modifySection = /###\s+Modify[\s\S]*?(?=###|^##\s|$)/m.exec(filesSection?.[0] ?? body);
    if (!createSection && !modifySection) {
        return null;
    }
    return {
        create: extractPathsFromSection(createSection?.[0] ?? '').map((p) => ({
            path: p,
            status: 'pending',
        })),
        modify: extractPathsFromSection(modifySection?.[0] ?? '').map((p) => ({
            path: p,
            status: 'pending',
        })),
        test: [],
    };
}
async function categorizeByExistence(paths, projectPath) {
    const create = [];
    const modify = [];
    for (const p of paths) {
        const full = join(projectPath, p);
        try {
            await stat(full);
            modify.push({ path: p, status: 'pending' });
        }
        catch {
            create.push({ path: p, status: 'pending' });
        }
    }
    return { create, modify, test: [] };
}
/**
 * Attempt to extract file paths from spec body for auto-populating ## Technical.
 * Returns null when no structured file section is found (caller uses placeholder).
 */
export async function extractFilesFromSpecBody(specBody, projectPath) {
    const structured = parseSectionedFileLists(specBody);
    if (structured !== null && (structured.create.length > 0 || structured.modify.length > 0)) {
        return structured;
    }
    const allPaths = [...new Set(Array.from(specBody.matchAll(FILE_PATH_RE), (m) => m[0]))];
    if (allPaths.length === 0) {
        return null;
    }
    return categorizeByExistence(allPaths, projectPath);
}
//# sourceMappingURL=technical-md-populator.js.map