import { readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { bootstrapThreadSuiteAdrs } from "./adr-bootstrap.js";
import { parseThreadSuiteSelfValidation, writeThreadSuiteAuditArtifacts, } from "./audit-artifacts.js";
import { writeThreadSuiteContextFiles } from "./context-writer.js";
import { createThreadSuiteContinuitySummary, writeThreadSuiteContinuitySummary, } from "./continuity-summary.js";
import { discoverDocsSemantics } from "./docs-reader.js";
import { discoverEntrypointSemantics } from "./entrypoint-scanner.js";
import { collectThreadSuiteEvidencePack } from "./evidence-pack.js";
import { discoverManifestSemantics } from "./manifest-parser.js";
import { createThreadSuiteMemoryEvents } from "./memory-bootstrap.js";
import { createThreadSuiteProjectIndex, writeThreadSuiteProjectIndex, } from "./project-index.js";
import { collectProjectInventory } from "./project-inventory.js";
import { createThreadSuiteSemanticDiscovery, mergeSemanticDiscovery, } from "./semantic-discovery.js";
import { createThreadSuiteValidationPlan } from "./validation.js";
export { bootstrapThreadSuiteAdrs } from "./adr-bootstrap.js";
export { buildThreadSuiteSelfValidationPrompt, parseThreadSuiteSelfValidation, writeThreadSuiteAuditArtifacts, } from "./audit-artifacts.js";
export { writeThreadSuiteContextFiles } from "./context-writer.js";
export { createThreadSuiteContinuitySummary, writeThreadSuiteContinuitySummary } from "./continuity-summary.js";
export { createThreadSuiteMemoryEvents } from "./memory-bootstrap.js";
export { enableThreadSuiteProjectMemory } from "./memory-settings.js";
export { createThreadSuiteProjectIndex, writeThreadSuiteProjectIndex } from "./project-index.js";
export { collectProjectInventory } from "./project-inventory.js";
export { synthesizeThreadSuiteProject } from "./synthesis-service.js";
export { createThreadSuiteValidationPlan } from "./validation.js";
const COMPLETE_GENERATED_TARGETS = [
    ".threadwell/continuity/state.json",
    ".threadwell/continuity/context.md",
    ".threadwell/continuity/plan.md",
    ".threadwell/continuity/queue.md",
    ".threadwell/continuity/decision-log.md",
    "STATE.md",
    "ACTIVE_QUEUE.md",
    "AUTONOMOUS_EXECUTION.md",
    "CONTEXT.md",
    "docs/adr/",
];
const AUDIT_GENERATED_TARGETS = [
    ".threadwell/project-map.json",
    ".threadwell/retrieval-routes.json",
    ".threadwell/risk-register.md",
    ".threadwell/agent-policy.md",
];
const LITE_GENERATED_TARGETS = COMPLETE_GENERATED_TARGETS.filter((path) => path !== "docs/adr/");
const DEFAULT_SKIPPED_ROOTS = [
    [".git", "git internals"],
    [".threadwell", "Threadwell runtime state"],
    [".pi", "legacy runtime state; use explicit adoption if supported later"],
    [".engram", "legacy runtime state; use explicit adoption if supported later"],
    ["node_modules", "dependencies"],
    ["target", "build output"],
    ["dist", "build output"],
    ["build", "build output"],
    ["coverage", "test output"],
    [".next", "framework build output"],
    [".turbo", "framework cache"],
    [".cache", "cache"],
];
export function parseThreadSuiteArgs(args) {
    const tokens = args.split(/\s+/u).filter(Boolean);
    return {
        mode: tokens.includes("--no-write") ? "preview" : "bootstrap",
        operation: tokens.includes("refresh") ? "refresh" : "bootstrap",
        profile: tokens.includes("lite") ? "lite" : "complete",
        deep: tokens.includes("--deep"),
        reset: tokens.includes("--reset"),
        adoptLegacy: tokens.includes("--adopt-legacy"),
    };
}
export async function createThreadSuitePreview(cwd, options) {
    const inventory = await collectProjectInventory(cwd, options);
    const entryNames = new Set(inventory.rootEntries);
    const scanRoots = inventory.rootEntries
        .filter((name) => !DEFAULT_SKIPPED_ROOTS.some(([root]) => root === name))
        .filter((name) => !name.startsWith("."))
        .slice(0, options.deep ? 80 : 40);
    const skippedRoots = inventory.skipped.filter((item) => entryNames.has(item.path));
    const projectType = inventory.projectType;
    const evidencePack = await collectThreadSuiteEvidencePack(cwd, inventory, options);
    const semanticDiscovery = await discoverThreadSuiteSemantics(cwd, inventory, options);
    const generatedTargets = options.profile === "complete"
        ? [...COMPLETE_GENERATED_TARGETS, ...AUDIT_GENERATED_TARGETS]
        : LITE_GENERATED_TARGETS;
    const writeTargets = await Promise.all(generatedTargets.map(async (path) => ({
        path,
        action: options.reset ? "update" : (await pathExists(join(cwd, path))) ? "preserve" : "create",
    })));
    const warnings = [];
    if (options.adoptLegacy) {
        warnings.push("Legacy adoption is planned but not implemented in the preview skeleton.");
    }
    const validationPlan = await createThreadSuiteValidationPlan(cwd, inventory);
    const memoryEvents = createThreadSuiteMemoryEvents(inventory, options, semanticDiscovery);
    const projectIndex = createThreadSuiteProjectIndex(inventory, options, semanticDiscovery);
    const projectIndexAction = options.mode === "bootstrap"
        ? await writeThreadSuiteProjectIndex(cwd, inventory, options, semanticDiscovery)
        : undefined;
    const continuitySummary = createThreadSuiteContinuitySummary(inventory, options);
    const continuitySummaryAction = options.mode === "bootstrap" ? await writeThreadSuiteContinuitySummary(cwd, inventory, options) : undefined;
    const writeActions = options.mode === "bootstrap"
        ? await writeThreadSuiteContextFiles(cwd, inventory, options, semanticDiscovery)
        : [];
    const adrActions = options.mode === "bootstrap" ? bootstrapThreadSuiteAdrs(cwd, inventory, options, semanticDiscovery) : [];
    return {
        cwd,
        mode: options.mode,
        operation: options.operation,
        profile: options.profile,
        projectType,
        inventory,
        semanticDiscovery,
        evidencePack,
        writeTargets,
        scanRoots,
        skippedRoots,
        warnings,
        projectIndex,
        projectIndexAction,
        continuitySummary,
        continuitySummaryAction,
        writeActions,
        adrActions,
        memoryEvents,
        validationPlan,
        auditArtifactActions: [],
    };
}
export async function validateThreadSuiteAuditArtifacts(cwd, client) {
    const [projectMap, retrievalRoutes, riskRegister, agentPolicy] = await Promise.all([
        readOptionalFile(cwd, ".threadwell/project-map.json"),
        readOptionalFile(cwd, ".threadwell/retrieval-routes.json"),
        readOptionalFile(cwd, ".threadwell/risk-register.md"),
        readOptionalFile(cwd, ".threadwell/agent-policy.md"),
    ]);
    const raw = await client.complete([
        "Validate these generated ThreadSuite artifacts using only their content.",
        'Return strict JSON: {"status":"pass|warn|fail","summary":"string","findings":["string"]}.',
        `project-map.json:\n${projectMap ?? "missing"}`,
        `retrieval-routes.json:\n${retrievalRoutes ?? "missing"}`,
        `risk-register.md:\n${riskRegister ?? "missing"}`,
        `agent-policy.md:\n${agentPolicy ?? "missing"}`,
    ].join("\n\n"));
    return parseThreadSuiteSelfValidation(raw);
}
export async function applyThreadSuiteSynthesis(cwd, preview, options, synthesis) {
    const writeOptions = { ...options, reset: true };
    const projectIndexAction = await writeThreadSuiteProjectIndex(cwd, preview.inventory, options, preview.semanticDiscovery, synthesis);
    const continuitySummaryAction = await writeThreadSuiteContinuitySummary(cwd, preview.inventory, options, synthesis);
    const writeActions = await writeThreadSuiteContextFiles(cwd, preview.inventory, writeOptions, preview.semanticDiscovery, synthesis);
    const adrActions = bootstrapThreadSuiteAdrs(cwd, preview.inventory, options, preview.semanticDiscovery, synthesis);
    const memoryEvents = createThreadSuiteMemoryEvents(preview.inventory, options, preview.semanticDiscovery, synthesis);
    const auditArtifactActions = options.profile === "complete" ? await writeThreadSuiteAuditArtifacts(cwd, synthesis) : [];
    preview.auditArtifactActions = auditArtifactActions;
    return { writeActions, adrActions, projectIndexAction, continuitySummaryAction, memoryEvents, auditArtifactActions };
}
export function renderThreadSuitePreview(preview, synthesis) {
    const lines = [
        preview.mode === "preview" ? "ThreadSuite preview" : "ThreadSuite bootstrap report",
        "",
        `CWD: ${preview.cwd}`,
        `Mode: ${preview.mode}`,
        `Operation: ${preview.operation}`,
        `Profile: ${preview.profile}`,
        `Detected project: ${preview.projectType}`,
        `Evidence: ${preview.evidencePack.items.length} files, ${preview.evidencePack.totalBytes} bytes`,
        `Evidence coverage: ${preview.evidencePack.coverage.manifestCount} manifests, ${preview.evidencePack.coverage.documentCount} docs, ${preview.evidencePack.coverage.entrypointCount} entrypoints, ${preview.evidencePack.coverage.truncatedCount} truncated`,
        "",
        "Semantic discovery:",
        `- Purpose: ${preview.semanticDiscovery.projectPurpose.value}`,
        ...formatList(preview.semanticDiscovery.commands.map((command) => `${command.name}: ${command.command}`), "No commands discovered from manifests/docs."),
        ...formatList(preview.semanticDiscovery.entrypoints.map((entrypoint) => `${entrypoint.path} — ${entrypoint.value}`), "No entrypoints discovered."),
        "",
        "Would scan:",
        ...formatList(preview.scanRoots, "No scan roots detected."),
        "",
        "Would skip:",
        ...formatList(preview.skippedRoots.map((item) => `${item.path} — ${item.reason}`), "No known generated/runtime roots detected."),
        "",
        "Would create/update/preserve:",
        ...preview.writeTargets.map((target) => `- ${target.action}: ${target.path}`),
    ];
    lines.push("", "Project index:", `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/project-index.json`);
    if (preview.profile === "complete") {
        lines.push("", "Audit layer:", `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/project-map.json`, `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/retrieval-routes.json`, `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/risk-register.md`, `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/agent-policy.md`);
    }
    lines.push("", "Operating memory:", `- ${preview.mode === "bootstrap" ? "write" : "would write"}: .threadwell/continuity/operating-memory.json`);
    if (synthesis) {
        lines.push("", "Model synthesis:", `- Purpose: ${synthesis.projectPurpose}`, `- Product: ${synthesis.productSummary}`, `- Architecture: ${synthesis.architecture.style}`, "- Components:", ...formatList(synthesis.architecture.components.map((component) => `${component.name}: ${component.responsibility}`), "No synthesized components."), "- Entrypoints:", ...formatList(synthesis.entrypoints.map((entrypoint) => `${entrypoint.path} — ${entrypoint.role}`), "No synthesized entrypoints."), "- Risks:", ...formatList(synthesis.risks.map((risk) => `${risk.risk}: ${risk.reason}`), "No synthesized risks."), "- Unknowns:", ...formatList(synthesis.unknowns.map((unknown) => `${unknown.question}: ${unknown.missingEvidence}`), "No synthesized unknowns."));
    }
    if (preview.writeActions.length > 0) {
        lines.push("", "Writes:", ...preview.writeActions.map((action) => `- ${action.action}: ${action.path}`));
    }
    if (preview.auditArtifactActions.length > 0) {
        lines.push("", "Audit artifacts:", ...preview.auditArtifactActions.map((action) => `- ${action.action}: ${action.path}`));
    }
    if (preview.selfValidation) {
        lines.push("", "Self-validation:", `- Status: ${preview.selfValidation.status}`, `- Summary: ${preview.selfValidation.summary}`, ...formatList(preview.selfValidation.findings, "No self-validation findings."));
    }
    if (preview.adrActions.length > 0) {
        lines.push("", "ADR bootstrap:", ...preview.adrActions.map((action) => `- ${action.action}: ${action.path} — ${action.title}`));
    }
    lines.push("", "Validation plan:", ...formatList(preview.validationPlan.commands, "No safe default validation commands detected."));
    if (preview.validationPlan.notes.length > 0) {
        lines.push(...preview.validationPlan.notes.map((note) => `- ${note}`));
    }
    if (preview.memoryEvents.length > 0) {
        lines.push("", "Memory capsules:", ...preview.memoryEvents.map((event) => `- ${event.summary}`));
    }
    if (preview.warnings.length > 0) {
        lines.push("", "Warnings:", ...preview.warnings.map((warning) => `- ${warning}`));
    }
    return lines.join("\n");
}
async function readOptionalFile(cwd, relativePath) {
    try {
        return await readFile(join(cwd, relativePath), "utf-8");
    }
    catch {
        return undefined;
    }
}
async function discoverThreadSuiteSemantics(cwd, inventory, options) {
    let discovery = createThreadSuiteSemanticDiscovery(inventory);
    if (options.profile === "lite")
        return discovery;
    discovery = mergeSemanticDiscovery(discovery, await discoverManifestSemantics(cwd, inventory));
    discovery = mergeSemanticDiscovery(discovery, await discoverDocsSemantics(cwd, inventory));
    discovery = mergeSemanticDiscovery(discovery, await discoverEntrypointSemantics(cwd, inventory));
    return discovery;
}
async function pathExists(path) {
    try {
        await stat(path);
        return true;
    }
    catch {
        return false;
    }
}
function formatList(items, empty) {
    return items.length > 0 ? items.map((item) => `- ${item}`) : [`- ${empty}`];
}
//# sourceMappingURL=index.js.map