"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.getAdrDirectoryPath = getAdrDirectoryPath;
exports.listAdrs = listAdrs;
exports.createAdr = createAdr;
exports.showAdrById = showAdrById;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const adrTemplate_1 = require("./adr/adrTemplate");
const adrLoader_1 = require("./adr/adrLoader");
const ADR_FILE_PATTERN = /^adr-(\d{3})-(.+)\.md$/i;
function toIdLabel(id) {
    return `ADR-${id.toString().padStart(3, '0')}`;
}
function slugifyTitle(title) {
    const normalized = title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
    return normalized.length > 0 ? normalized : 'decision';
}
async function ensureDirectoryExists(targetPath) {
    await node_fs_1.promises.mkdir(targetPath, { recursive: true });
}
async function readAdrTemplate(workspaceRoot) {
    const templatePath = path.join(await getAdrDirectoryPath(workspaceRoot), adrTemplate_1.ADR_TEMPLATE_FILE_NAME);
    try {
        return await node_fs_1.promises.readFile(templatePath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return adrTemplate_1.canonicalAdrTemplate;
        }
        throw error;
    }
}
function parseTitleFromContent(content, fallbackSlug) {
    const lines = content.split(/\r?\n/);
    for (const line of lines) {
        const match = line.match(/^#\s*ADR-\d{3}\s*:\s*(.+)$/i);
        if (match && match[1].trim().length > 0) {
            return match[1].trim();
        }
    }
    return fallbackSlug
        .split('-')
        .map((segment) => (segment.length > 0 ? `${segment[0].toUpperCase()}${segment.slice(1)}` : ''))
        .join(' ')
        .trim();
}
async function getAdrDirectoryPath(workspaceRoot) {
    const adrDirectoryRelativePath = await (0, adrLoader_1.resolveAdrDirectoryRelativePath)(workspaceRoot);
    return (0, adrLoader_1.getAdrDirectoryPath)(workspaceRoot, adrDirectoryRelativePath);
}
async function listAdrs(workspaceRoot) {
    const adrDirectory = await getAdrDirectoryPath(workspaceRoot);
    try {
        const entries = await node_fs_1.promises.readdir(adrDirectory, { withFileTypes: true });
        const records = [];
        for (const entry of entries) {
            if (!entry.isFile()) {
                continue;
            }
            const match = entry.name.match(ADR_FILE_PATTERN);
            if (!match) {
                continue;
            }
            const id = Number(match[1]);
            if (!Number.isFinite(id)) {
                continue;
            }
            const filePath = path.join(adrDirectory, entry.name);
            let content = '';
            try {
                content = await node_fs_1.promises.readFile(filePath, { encoding: 'utf8' });
            }
            catch {
                content = '';
            }
            const fallbackSlug = match[2] ?? '';
            const title = parseTitleFromContent(content, fallbackSlug);
            records.push({
                id,
                idLabel: toIdLabel(id),
                fileName: entry.name,
                filePath,
                title,
            });
        }
        return records.sort((left, right) => left.id - right.id);
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        }
        throw error;
    }
}
async function createAdr(workspaceRoot, title) {
    const trimmedTitle = title.trim();
    if (!trimmedTitle) {
        throw new Error('ADR title must not be empty.');
    }
    const existing = await listAdrs(workspaceRoot);
    const nextId = (existing[existing.length - 1]?.id ?? 0) + 1;
    const idLabel = toIdLabel(nextId);
    const slug = slugifyTitle(trimmedTitle);
    const fileName = `adr-${nextId.toString().padStart(3, '0')}-${slug}.md`;
    const adrDirectory = await getAdrDirectoryPath(workspaceRoot);
    const filePath = path.join(adrDirectory, fileName);
    await ensureDirectoryExists(adrDirectory);
    const template = await readAdrTemplate(workspaceRoot);
    await node_fs_1.promises.writeFile(filePath, (0, adrTemplate_1.renderAdrTemplate)(template, {
        adrId: idLabel,
        title: trimmedTitle,
    }), { encoding: 'utf8' });
    return {
        record: {
            id: nextId,
            idLabel,
            fileName,
            filePath,
            title: trimmedTitle,
        },
    };
}
async function showAdrById(workspaceRoot, idInput) {
    const numeric = Number(idInput.trim());
    if (!Number.isFinite(numeric) || numeric <= 0 || !Number.isInteger(numeric)) {
        return { kind: 'missing' };
    }
    const id = numeric;
    const entries = await listAdrs(workspaceRoot);
    const target = entries.find((entry) => entry.id === id);
    if (!target) {
        return { kind: 'missing' };
    }
    const content = await node_fs_1.promises.readFile(target.filePath, { encoding: 'utf8' });
    return { kind: 'ok', record: target, content };
}
//# sourceMappingURL=adrManagement.js.map