"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.importContextExports = importContextExports;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
function section(content, header) {
    const idx = content.indexOf(header);
    if (idx === -1)
        return null;
    const rest = content.slice(idx + header.length);
    const next = rest.search(/\n##\s+/);
    const chunk = next === -1 ? rest : rest.slice(0, next);
    return chunk.trim();
}
function bullets(block) {
    if (!block)
        return null;
    const lines = block.split("\n").map((l) => l.trim());
    const items = lines
        .filter((l) => l.startsWith("- "))
        .map((l) => l.replace(/^-+\s*/, "").trim())
        .filter(Boolean);
    return items.length ? items : null;
}
function mdId(text) {
    // Stable-ish local ID for imports (not a UUID); avoids churn.
    return text
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/(^-|-$)/g, "")
        .slice(0, 64) || "item";
}
function parseFeatureBlocks(md) {
    const blocks = md.split(/\n---\s*\n/);
    const out = [];
    for (const block of blocks) {
        const nameMatch = block.match(/^###\s+(.+?)(?:\s+\((HIGH|MEDIUM|LOW)\))?\s*$/m);
        if (!nameMatch?.[1])
            continue;
        const name = nameMatch[1].trim();
        const priority = (nameMatch[2] || "medium").toLowerCase();
        const descMatch = block.match(/^\*\*Description:\*\*\s*(.+)\s*$/m);
        const valueMatch = block.match(/^\*\*Value:\*\*\s*(.+)\s*$/m);
        const acBlock = section(block, "**Acceptance Criteria:**");
        const acceptanceCriteria = (acBlock
            ? acBlock
                .split("\n")
                .map((l) => l.trim())
                .filter((l) => l.startsWith("-"))
                .map((l) => l.replace(/^-+\s*(?:\[[ xX]\]\s*)?/, "").trim())
                .filter(Boolean)
            : []) || [];
        out.push({
            id: mdId(name),
            name,
            description: descMatch?.[1]?.trim() || "",
            priority: priority === "high" || priority === "low" ? priority : "medium",
            userValue: valueMatch?.[1]?.trim() || "",
            acceptanceCriteria,
            dependencies: [],
        });
    }
    return out.length ? out : null;
}
function parseFlowBlocks(md) {
    const blocks = md.split(/\n---\s*\n/);
    const out = [];
    for (const block of blocks) {
        const nameMatch = block.match(/^###\s+(.+?)\s*$/m);
        if (!nameMatch?.[1])
            continue;
        const name = nameMatch[1].trim();
        const descMatch = block.match(/^\*\*Description:\*\*\s*(.+)\s*$/m);
        const actorsMatch = block.match(/^\*\*Actors:\*\*\s*(.+)\s*$/m);
        const stepsBlock = section(block, "**Steps:**");
        const steps = (stepsBlock
            ? stepsBlock
                .split("\n")
                .map((l) => l.trim())
                .filter((l) => /^\d+\.\s+/.test(l))
                .map((l) => l.replace(/^\d+\.\s+/, "").trim())
                .filter(Boolean)
            : []) || [];
        const actors = actorsMatch?.[1]
            ? actorsMatch[1].split(",").map((s) => s.trim()).filter(Boolean)
            : [];
        out.push({
            id: mdId(name),
            name,
            description: descMatch?.[1]?.trim() || "",
            steps,
            actors,
        });
    }
    return out.length ? out : null;
}
function parseEdgeCaseBlocks(md) {
    const blocks = md.split(/\n---\s*\n/);
    const out = [];
    for (const block of blocks) {
        const h = block.match(/^###\s+\[(.+?)\]\s+(.+?)\s*$/m);
        if (!h?.[2])
            continue;
        const category = h[1]?.trim() || "General";
        const description = h[2].trim();
        const mitigationMatch = block.match(/^\*\*Mitigation:\*\*\s*(.+)\s*$/m);
        out.push({
            id: mdId(`${category}-${description}`),
            category,
            description,
            mitigation: mitigationMatch?.[1]?.trim() || "",
        });
    }
    return out.length ? out : null;
}
async function importContextExports(contextDir, base) {
    const updated = {
        ...base,
        prd: { ...base.prd },
        features: Array.isArray(base.features) ? [...base.features] : [],
        flows: Array.isArray(base.flows) ? [...base.flows] : [],
        edgeCases: Array.isArray(base.edgeCases) ? [...base.edgeCases] : [],
    };
    const prdPath = path.join(contextDir, "01-prd.md");
    if (await fs.pathExists(prdPath)) {
        const prdMd = await fs.readFile(prdPath, "utf8");
        const corePurpose = section(prdMd, "## Core Purpose");
        if (corePurpose)
            updated.prd.problemStatement = corePurpose;
        const goals = bullets(section(prdMd, "## Goals"));
        if (goals)
            updated.prd.goals = goals;
        const nonGoals = bullets(section(prdMd, "## Non-Goals"));
        if (nonGoals)
            updated.prd.nonGoals = nonGoals;
        const targetAudience = section(prdMd, "## Target Audience");
        if (targetAudience)
            updated.prd.targetAudience = targetAudience;
        const successMetrics = bullets(section(prdMd, "## Success Metrics"));
        if (successMetrics)
            updated.prd.successMetrics = successMetrics;
        // Best-effort: if a user edited the PRD title, keep it
        const titleMatch = prdMd.match(/^\*\*Project Name:\*\*\s*(.+)\s*$/m);
        if (titleMatch?.[1])
            updated.prd.title = String(titleMatch[1]).trim();
    }
    const featuresPath = path.join(contextDir, "01a-features.md");
    if (await fs.pathExists(featuresPath)) {
        const featuresMd = await fs.readFile(featuresPath, "utf8");
        const parsed = parseFeatureBlocks(featuresMd);
        if (parsed)
            updated.features = parsed;
    }
    const flowsPath = path.join(contextDir, "01b-user-flows.md");
    if (await fs.pathExists(flowsPath)) {
        const flowsMd = await fs.readFile(flowsPath, "utf8");
        const parsed = parseFlowBlocks(flowsMd);
        if (parsed)
            updated.flows = parsed;
    }
    const edgeCasesPath = path.join(contextDir, "01c-edge-cases.md");
    if (await fs.pathExists(edgeCasesPath)) {
        const edgeCasesMd = await fs.readFile(edgeCasesPath, "utf8");
        const parsed = parseEdgeCaseBlocks(edgeCasesMd);
        if (parsed)
            updated.edgeCases = parsed;
    }
    return updated;
}
//# sourceMappingURL=contextExportsImporter.js.map