import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import matter from "gray-matter";
import { getPlanningDir } from "./config.js";
const STAGE_ORDER = ["research", "brief", "adr", "impl", "retrospective"];
function parseFrontmatter(filePath) {
    if (!existsSync(filePath))
        return null;
    const raw = readFileSync(filePath, "utf-8");
    const { data } = matter(raw);
    return {
        title: data.title ?? "",
        date: data.date ?? "",
        status: data.status ?? "",
    };
}
function parseDependsOn(filePath) {
    if (!existsSync(filePath))
        return [];
    const content = readFileSync(filePath, "utf-8");
    const depsMatch = content.match(/## Depends On\s*\n([\s\S]*?)(?=\n## |\n$|$)/);
    if (!depsMatch)
        return [];
    const deps = [];
    for (const line of depsMatch[1].split("\n")) {
        const match = line.match(/^-\s+`?(?:\.indusk\/)?planning\/([^/`]+)\/?`?/);
        if (match) {
            deps.push(match[1]);
        }
    }
    return deps;
}
function determineStage(planDir, docs) {
    // Walk stages in reverse to find the most advanced document
    for (let i = STAGE_ORDER.length - 1; i >= 0; i--) {
        const stage = STAGE_ORDER[i];
        const file = `${stage}.md`;
        if (docs.includes(file)) {
            const fm = parseFrontmatter(join(planDir, file));
            return { stage, stageStatus: fm?.status ?? "unknown" };
        }
    }
    return { stage: "unknown", stageStatus: "unknown" };
}
function determineNextStep(stage, stageStatus) {
    if (stage === "unknown")
        return "Create a brief";
    const idx = STAGE_ORDER.indexOf(stage);
    if (stageStatus === "completed" || stageStatus === "accepted") {
        const next = STAGE_ORDER[idx + 1];
        if (next)
            return `Create ${next}`;
        return "Done";
    }
    if (stageStatus === "in-progress") {
        return `Continue ${stage}`;
    }
    return `Review ${stage} (status: ${stageStatus})`;
}
export function parsePlan(planDir) {
    const name = planDir.split("/").pop() ?? "";
    const entries = readdirSync(planDir).filter((f) => f.endsWith(".md"));
    const { stage, stageStatus } = determineStage(planDir, entries);
    const dependencies = parseDependsOn(join(planDir, "brief.md"));
    const nextStep = determineNextStep(stage, stageStatus);
    return {
        name,
        stage,
        stageStatus,
        nextStep,
        dependencies,
        documents: entries,
    };
}
export function parseAllPlans(projectRoot) {
    const planningDir = getPlanningDir(projectRoot);
    if (!existsSync(planningDir))
        return [];
    return readdirSync(planningDir, { withFileTypes: true })
        .filter((d) => d.isDirectory())
        .map((d) => parsePlan(join(planningDir, d.name)))
        .sort((a, b) => a.name.localeCompare(b.name));
}
