import { existsSync, readFileSync } from "node:fs";
import matter from "gray-matter";
const GATE_SUFFIXES = {
    Verification: "verification",
    Context: "context",
    Document: "document",
};
function parseChecklistItems(lines) {
    const items = [];
    for (const line of lines) {
        const match = line.match(/^-\s+\[([ x])\]\s+(.*)/);
        if (match) {
            items.push({
                checked: match[1] === "x",
                text: match[2].trim(),
            });
        }
    }
    return items;
}
export function parseImplString(raw) {
    const { data, content } = matter(raw);
    const title = data.title ?? "";
    const status = data.status ?? "";
    const lines = content.split("\n");
    const phases = [];
    let currentPhase = null;
    let currentGateType = "implementation";
    let currentGateLines = [];
    let inForwardIntelligence = false;
    let forwardIntelligenceLines = [];
    function flushGate() {
        if (!currentPhase)
            return;
        const items = parseChecklistItems(currentGateLines);
        if (items.length > 0) {
            currentPhase.gates.push({ type: currentGateType, items });
        }
        currentGateLines = [];
    }
    for (const line of lines) {
        // Phase header: ### Phase N: Name
        const phaseMatch = line.match(/^###\s+Phase\s+(\d+)[:\s]+(.*)/);
        if (phaseMatch) {
            flushGate();
            if (currentPhase)
                phases.push(currentPhase);
            currentPhase = {
                number: Number.parseInt(phaseMatch[1], 10),
                name: phaseMatch[2].trim(),
                gates: [],
                blocker: null,
                forwardIntelligence: null,
            };
            currentGateType = "implementation";
            currentGateLines = [];
            continue;
        }
        // Forward Intelligence header: #### Phase N Forward Intelligence
        const fiMatch = line.match(/^####\s+Phase\s+\d+\s+Forward Intelligence\b/);
        if (fiMatch) {
            flushGate();
            inForwardIntelligence = true;
            forwardIntelligenceLines = [];
            continue;
        }
        // Gate header: #### Phase N Verification|Context|Document
        const gateMatch = line.match(/^####\s+Phase\s+\d+\s+(Verification|Context|Document)\b/);
        if (gateMatch) {
            if (inForwardIntelligence && currentPhase) {
                currentPhase.forwardIntelligence = forwardIntelligenceLines.join("\n").trim() || null;
                inForwardIntelligence = false;
            }
            flushGate();
            currentGateType = GATE_SUFFIXES[gateMatch[1]];
            continue;
        }
        // Blocker line: blocker: description
        if (currentPhase) {
            const blockerMatch = line.match(/^blocker:\s+(.*)/);
            if (blockerMatch) {
                currentPhase.blocker = blockerMatch[1].trim();
                continue;
            }
        }
        if (inForwardIntelligence) {
            forwardIntelligenceLines.push(line);
        }
        else {
            currentGateLines.push(line);
        }
    }
    // Flush last forward intelligence, gate, and phase
    if (inForwardIntelligence && currentPhase) {
        currentPhase.forwardIntelligence = forwardIntelligenceLines.join("\n").trim() || null;
    }
    flushGate();
    if (currentPhase)
        phases.push(currentPhase);
    return { title, status, phases };
}
export function parseImpl(filePath) {
    if (!existsSync(filePath)) {
        return { title: "", status: "", phases: [] };
    }
    return parseImplString(readFileSync(filePath, "utf-8"));
}
export function getPhaseCompletion(phase) {
    const uncheckedByGate = {
        implementation: [],
        verification: [],
        context: [],
        document: [],
    };
    let totalItems = 0;
    let checkedItems = 0;
    for (const gate of phase.gates) {
        for (const item of gate.items) {
            totalItems++;
            if (item.checked) {
                checkedItems++;
            }
            else {
                uncheckedByGate[gate.type].push(item.text);
            }
        }
    }
    return {
        phase: phase.number,
        name: phase.name,
        complete: checkedItems === totalItems,
        totalItems,
        checkedItems,
        uncheckedByGate,
    };
}
export function getAllPhaseCompletions(parsed) {
    return parsed.phases.map(getPhaseCompletion);
}
