import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { createAdrFileName, createAdrMarkdown, ensureAdrDir, getAdrDir, parseAdrMarkdown, readAdrIndex, } from "./adr-format.js";
export class AdrService {
    projectRoot;
    constructor(options) {
        this.projectRoot = options.projectRoot;
    }
    getIndex() {
        return readAdrIndex(this.projectRoot);
    }
    createProposedAdr(input) {
        const dir = ensureAdrDir(this.projectRoot);
        const idNumber = this.nextAdrNumber();
        const id = `ADR-${String(idNumber).padStart(4, "0")}`;
        const record = {
            ...input,
            id,
            status: "proposed",
            date: input.date ?? new Date().toISOString().slice(0, 10),
        };
        const path = join(dir, createAdrFileName(idNumber, input.title));
        writeFileSync(path, createAdrMarkdown(record), "utf-8");
        return { ...record, path };
    }
    acceptAdr(id) {
        return this.updateAdr(id, (record) => ({ ...record, status: "accepted" }));
    }
    supersedeAdr(id, supersededBy) {
        return this.updateAdr(id, (record) => ({ ...record, status: "superseded", supersededBy }));
    }
    getActiveAdrs() {
        return this.getIndex().active;
    }
    nextAdrNumber() {
        const dir = ensureAdrDir(this.projectRoot);
        const numbers = readdirSync(dir)
            .map((entry) => entry.match(/^(\d{4})-/)?.[1])
            .filter((entry) => Boolean(entry))
            .map((entry) => Number.parseInt(entry, 10));
        return numbers.length === 0 ? 1 : Math.max(...numbers) + 1;
    }
    findAdrPath(id) {
        const dir = getAdrDir(this.projectRoot);
        if (!existsSync(dir))
            return undefined;
        return readdirSync(dir)
            .map((entry) => join(dir, entry))
            .find((path) => parseAdrMarkdown(readFileSync(path, "utf-8"), path)?.id === id);
    }
    updateAdr(id, update) {
        const path = this.findAdrPath(id);
        if (!path)
            return undefined;
        const current = parseAdrMarkdown(readFileSync(path, "utf-8"), path);
        if (!current)
            return undefined;
        const next = { ...update(current), path };
        writeFileSync(path, createAdrMarkdown(next), "utf-8");
        return next;
    }
}
//# sourceMappingURL=adr-service.js.map