import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
const THREADSUITE_SECTION_START = "<!-- THREADSUITE:START -->";
const THREADSUITE_SECTION_END = "<!-- THREADSUITE:END -->";
export async function writeThreadSuiteContextFiles(cwd, inventory, options, semanticDiscovery, synthesis) {
    const targets = buildTargets(inventory, options.profile, semanticDiscovery, synthesis);
    const actions = [];
    for (const target of targets) {
        const path = join(cwd, target.path);
        const existing = await readExisting(path);
        if (existing === undefined) {
            await mkdir(dirname(path), { recursive: true });
            await writeFile(path, target.content, "utf-8");
            actions.push({ path: target.path, action: "created" });
            continue;
        }
        if (!options.reset) {
            actions.push({ path: target.path, action: "preserved" });
            continue;
        }
        await writeFile(path, replaceGeneratedContent(existing, target), "utf-8");
        actions.push({ path: target.path, action: "updated" });
    }
    return actions;
}
function buildTargets(inventory, _profile, semanticDiscovery, synthesis) {
    const targets = [
        { path: ".threadwell/continuity/state.json", content: buildContinuityState(inventory) },
        {
            path: ".threadwell/continuity/context.md",
            content: buildContextMarkdown(inventory, semanticDiscovery, synthesis),
        },
        { path: ".threadwell/continuity/queue.md", content: buildQueueMarkdown(inventory) },
        { path: ".threadwell/continuity/plan.md", content: buildPlanMarkdown(inventory) },
        { path: ".threadwell/continuity/decision-log.md", content: buildDecisionLogMarkdown(inventory) },
        { path: "STATE.md", content: buildStateMarkdown(inventory) },
        { path: "ACTIVE_QUEUE.md", content: buildActiveQueueMarkdown(inventory) },
        { path: "AUTONOMOUS_EXECUTION.md", content: buildAutonomousExecutionMarkdown(inventory) },
        { path: "CONTEXT.md", content: buildContextMarkdown(inventory, semanticDiscovery, synthesis) },
    ];
    return targets;
}
async function readExisting(path) {
    try {
        return await readFile(path, "utf-8");
    }
    catch {
        return undefined;
    }
}
function replaceGeneratedContent(existing, target) {
    if (target.path.endsWith(".json")) {
        return target.content;
    }
    return replaceThreadSuiteSection(existing, target.content);
}
function replaceThreadSuiteSection(existing, generated) {
    const section = wrapThreadSuiteSection(generated);
    const start = existing.indexOf(THREADSUITE_SECTION_START);
    const end = existing.indexOf(THREADSUITE_SECTION_END);
    if (start >= 0 && end > start) {
        return `${existing.slice(0, start)}${section}${existing.slice(end + THREADSUITE_SECTION_END.length)}`;
    }
    return `${existing.trimEnd()}\n\n${section}\n`;
}
function wrapThreadSuiteSection(content) {
    return `${THREADSUITE_SECTION_START}\n${content.trim()}\n${THREADSUITE_SECTION_END}`;
}
function buildContinuityState(inventory) {
    return `${JSON.stringify({
        status: "active",
        source: "threadsuite-bootstrap",
        projectType: inventory.projectType,
        confidence: inventory.confidence,
    }, null, 2)}\n`;
}
function buildContextMarkdown(inventory, semanticDiscovery, synthesis) {
    return [
        "# CONTEXT",
        "",
        "Generated by ThreadSuite. Review inferred facts before treating them as authoritative.",
        "",
        "## Project",
        "",
        inventory.projectType,
        "",
        "## Purpose",
        "",
        synthesis?.projectPurpose ?? semanticDiscovery.projectPurpose.value,
        "",
        "## Terms",
        "",
        ...formatContextTerms(synthesis?.domainConcepts ?? []),
        "",
        "## Conventions",
        "",
        "- **ThreadSuite sources first**: Consult continuity, CONTEXT.md, ADRs, memory, and project index before broad repository exploration.",
        "",
        "## Open Questions",
        "",
        ...formatOpenQuestions(synthesis),
        "",
        "## Project identity",
        "",
        `- Inferred type: ${inventory.projectType}`,
        `- Purpose: ${semanticDiscovery.projectPurpose.value}`,
        `- Confidence: ${inventory.confidence}`,
        `- Purpose sources: ${formatInlineSources(semanticDiscovery.projectPurpose.sources)}`,
        "- Source: bounded ThreadSuite inventory",
        "",
        ...(synthesis
            ? [
                "## Synthesized project intelligence",
                "",
                `- Purpose: ${synthesis.projectPurpose}`,
                `- Product summary: ${synthesis.productSummary}`,
                `- Architecture style: ${synthesis.architecture.style}`,
                "- Components:",
                ...synthesis.architecture.components.map((component) => `  - ${component.name}: ${component.responsibility} (${formatInlineSources(component.evidence)})`),
                "",
            ]
            : []),
        "## Source of truth",
        "",
        "- STATE.md: current project status and checkpoints",
        "- ACTIVE_QUEUE.md: executable task queue",
        "- AUTONOMOUS_EXECUTION.md: continuity operating contract",
        "- CONTEXT.md: semantic project map",
        "- docs/adr/: proposed/accepted architecture decisions",
        "- .threadwell/project-index.json: generated machine-readable inventory",
        "",
        "## Architecture map",
        "",
        "- Inferred manifests:",
        ...formatFiles(inventory.manifests),
        "- Inferred source roots:",
        ...formatList(inventory.sourceRoots),
        "- Inferred test roots:",
        ...formatList(inventory.testRoots),
        "",
        "## Core flows",
        "",
        "- Project bootstrap starts with `/threadsuite`.",
        "- Future prompts should consult continuity, context, ADRs, memory, and project index before broad repository exploration.",
        "- Inferred facts must be reviewed before becoming authoritative decisions.",
        "",
        "## Important modules",
        "",
        ...formatList(inventory.sourceRoots),
        "",
        "## Commands",
        "",
        ...formatCommands(semanticDiscovery.commands),
        "",
        "## Validation strategy",
        "",
        ...formatClaims(semanticDiscovery.validationStrategy, "Unknown until validated; prefer lightweight checks before heavy builds/tests."),
        "",
        "## User preferences",
        "",
        "- Preserve user-authored files by default.",
        "- Prefer complete ThreadSuite bootstrap; use `lite` only when explicitly requested.",
        "",
        "## Product decisions",
        "",
        "- Generated decisions are proposed ADR candidates, not accepted facts.",
        "",
        "## Known risks",
        "",
        ...formatClaims(semanticDiscovery.risks, "No project-specific risks detected from bounded evidence."),
        "- Generated context can become stale; run refresh after significant project changes.",
        "- Inferred architecture can be wrong; review generated facts.",
        "",
        "## Anti-patterns / Do not do",
        "",
        "- Do not overwrite user-authored continuity/context files without explicit reset.",
        "- Do not start with broad repository exploration when primary ThreadSuite sources exist.",
        "- Do not treat inferred ADR candidates as accepted decisions.",
        "",
        "## Glossary",
        "",
        "- ThreadSuite: project bootstrap that seeds continuity, context, ADRs, memory, and inventory.",
        "- Complete profile: default full bootstrap.",
        "- Lite profile: intentionally smaller bootstrap.",
        "",
        "## Generated facts needing review",
        "",
        ...formatClaims(semanticDiscovery.unknowns, "No unknowns detected."),
        ...formatFiles(inventory.documents),
        "",
        "## Skipped inventory",
        ...formatSkipped(inventory.skipped),
    ].join("\n");
}
function formatContextTerms(domainConcepts) {
    if (domainConcepts.length === 0)
        return ["- **Project vocabulary**: Review generated project concepts before accepting stable terms."];
    return domainConcepts
        .slice(0, 20)
        .map((concept) => `- **${concept}**: Inferred project concept from ThreadSuite synthesis.`);
}
function formatOpenQuestions(synthesis) {
    if (!synthesis || synthesis.unknowns.length === 0)
        return ["- Review generated facts and ADR candidates before treating them as authoritative."];
    return synthesis.unknowns
        .slice(0, 20)
        .map((unknown) => `- ${unknown.question} Missing evidence: ${unknown.missingEvidence}`);
}
function buildQueueMarkdown(inventory) {
    return [
        "# ThreadSuite queue",
        "",
        "- [ ] Review generated CONTEXT.md inferred facts.",
        "- [ ] Confirm project commands and validation strategy.",
        ...(inventory.adrFiles.length > 0 ? ["- [ ] Review existing ADRs for current decisions."] : []),
    ].join("\n");
}
function buildPlanMarkdown(inventory) {
    return [
        "# ThreadSuite plan",
        "",
        `Project type: ${inventory.projectType}`,
        "",
        "Next: review generated context and queue.",
    ].join("\n");
}
function buildDecisionLogMarkdown(inventory) {
    return [
        "# Decision log",
        "",
        "No authoritative decisions were inferred by ThreadSuite.",
        `Detected project type candidate: ${inventory.projectType}.`,
    ].join("\n");
}
function buildStateMarkdown(inventory) {
    return [
        "---",
        "status: active",
        "source: threadsuite-bootstrap",
        "---",
        "",
        "# STATE",
        "",
        `ThreadSuite initialized project context with ${inventory.confidence} confidence.`,
        "",
        "Next: review CONTEXT.md and ACTIVE_QUEUE.md.",
    ].join("\n");
}
function buildActiveQueueMarkdown(inventory) {
    return [
        "# ACTIVE_QUEUE.md",
        "",
        "## Queue",
        "",
        "### T001 — Review ThreadSuite generated context",
        "",
        "Status: pending",
        "Scope:",
        `- Review inferred ${inventory.projectType} project context and confirm or edit generated facts.`,
    ].join("\n");
}
function buildAutonomousExecutionMarkdown(inventory) {
    return [
        "# AUTONOMOUS_EXECUTION.md",
        "",
        "Use STATE.md, ACTIVE_QUEUE.md, CONTEXT.md, and ADRs as primary sources before broad repository exploration.",
        `Detected project type: ${inventory.projectType}.`,
    ].join("\n");
}
function formatCommands(commands) {
    return commands.length > 0
        ? commands.map((command) => `- ${command.name}: \`${command.command}\` (${formatInlineSources(command.sources)})`)
        : ["- Unknown until validated; review manifests and docs."];
}
function formatClaims(claims, empty) {
    return claims.length > 0
        ? claims.map((claim) => `- ${claim.value} (${formatInlineSources(claim.sources)})`)
        : [`- ${empty}`];
}
function formatInlineSources(sources) {
    return sources.length > 0 ? sources.join(", ") : "no direct source";
}
function formatFiles(files) {
    return files.length > 0 ? files.map((file) => `- ${file.path} (${file.sizeBytes} bytes)`) : ["- none detected"];
}
function formatList(items) {
    return items.length > 0 ? items.map((item) => `- ${item}`) : ["- none detected"];
}
function formatSkipped(items) {
    return items.length > 0 ? items.map((item) => `- ${item.path}: ${item.reason}`) : ["- none"];
}
//# sourceMappingURL=context-writer.js.map