import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const ACTIVE_QUEUE_FILE = "ACTIVE_QUEUE.md";
export const FEATURE_PACKET_DIR = ".threadwell/features";
export function createFeatureSlug(title) {
    return title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-|-$/g, "")
        .slice(0, 80);
}
export function createFeatureId(title) {
    const date = new Date().toISOString().slice(0, 10).replaceAll("-", "");
    return `${date}-${createFeatureSlug(title) || "feature"}`;
}
export function getFeaturePacketDir(projectRoot) {
    return join(projectRoot, FEATURE_PACKET_DIR);
}
export function getFeaturePacketPath(projectRoot, id) {
    return join(getFeaturePacketDir(projectRoot), id, "feature.md");
}
export function createFeaturePacket(title, goal) {
    return {
        id: createFeatureId(title),
        title,
        status: "draft",
        goal,
        contextTerms: [],
        adrIds: [],
        tasks: [],
    };
}
export function renderFeaturePacket(packet) {
    return `# ${packet.title}

Id: ${packet.id}
Status: ${packet.status}

## Goal

${packet.goal}

## Context Terms

${packet.contextTerms.length > 0 ? packet.contextTerms.map((term) => `- ${term}`).join("\n") : "- none"}

## ADRs

${packet.adrIds.length > 0 ? packet.adrIds.map((id) => `- ${id}`).join("\n") : "- none"}

## Tasks

${packet.tasks.length > 0 ? packet.tasks.map((task) => `- [${task.status}] ${task.id}: ${task.title}\n  ${task.description}`).join("\n") : "- none"}
`;
}
export function writeFeaturePacket(projectRoot, packet) {
    const dir = join(getFeaturePacketDir(projectRoot), packet.id);
    mkdirSync(dir, { recursive: true });
    const path = getFeaturePacketPath(projectRoot, packet.id);
    writeFileSync(path, renderFeaturePacket(packet), "utf-8");
    return path;
}
export function readFeaturePacket(projectRoot, id) {
    const path = getFeaturePacketPath(projectRoot, id);
    if (!existsSync(path))
        return undefined;
    return readFileSync(path, "utf-8");
}
export function parseFeatureTasks(markdown) {
    const taskMatches = markdown.matchAll(/^- \[(pending|in_progress|done|blocked|partial|cancelled)\] ([^:\n]+): (.+)$/gmu);
    return [...taskMatches].map((match) => ({
        status: match[1],
        id: match[2].trim(),
        title: match[3].trim(),
        description: "Synced from Feature Packet.",
    }));
}
export function syncFeaturePacketTasksToActiveQueue(projectRoot, featureId) {
    const featureMarkdown = readFeaturePacket(projectRoot, featureId);
    if (!featureMarkdown)
        return { added: 0, path: getFeaturePacketPath(projectRoot, featureId) };
    const queuePath = join(projectRoot, ACTIVE_QUEUE_FILE);
    if (!existsSync(queuePath))
        return { added: 0, path: queuePath };
    const queueMarkdown = readFileSync(queuePath, "utf-8");
    const tasks = parseFeatureTasks(featureMarkdown).filter((task) => !queueMarkdown.includes(`feature:${featureId}:${task.id}`));
    if (tasks.length === 0)
        return { added: 0, path: queuePath };
    const nextId = getNextQueueTaskNumber(queueMarkdown);
    const renderedTasks = tasks.map((task, index) => renderQueueTask(nextId + index, featureId, task)).join("\n");
    writeFileSync(queuePath, `${queueMarkdown.trimEnd()}\n\n${renderedTasks}\n`, "utf-8");
    return { added: tasks.length, path: queuePath };
}
function getNextQueueTaskNumber(queueMarkdown) {
    const ids = [...queueMarkdown.matchAll(/^### T(\d+)\s+[—-]/gmu)].map((match) => Number.parseInt(match[1], 10));
    return ids.length > 0 ? Math.max(...ids) + 1 : 1;
}
function renderQueueTask(number, featureId, task) {
    const id = `T${String(number).padStart(3, "0")}`;
    return `### ${id} — ${task.title}

Status: ${task.status}
Claimed by:
Started:
Last update:
Scope:
- ${task.description}
DoD:
- Feature task is completed or explicitly re-scoped.
Validation:
- Follow feature-specific validation.
Files likely touched:
- TBD
Risk: medium
Depends on:
- none
Notes:
- Synced from feature:${featureId}:${task.id}
`;
}
//# sourceMappingURL=feature-format.js.map