"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeLlmsTxt = writeLlmsTxt;
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const HEADER_RX = /^#\s/m;
function escapeMarkdown(text) {
    return text.replace(/[\[\]\(\)\n\r]/g, " ").trim();
}
function summariseBody(body) {
    const flat = body.replace(/\s+/g, " ").trim();
    if (flat.length <= 200)
        return flat;
    return flat.slice(0, 197).trimEnd() + "…";
}
async function writeLlmsTxt(input, deps) {
    const session = deps.getSession();
    let rows = [];
    let skippedNoUrl = 0;
    try {
        const r = await session.run(`MATCH (d:KnowledgeDocument {accountId: $accountId})
       RETURN d.title AS title, d.url AS url, d.summary AS summary,
              coalesce(d.body, d.abstract, '') AS body
       ORDER BY d.title ASC`, { accountId: input.accountId });
        for (const rec of r.records) {
            const title = rec.get("title") ?? "";
            const url = rec.get("url") ?? "";
            const summary = rec.get("summary") ?? "";
            const body = rec.get("body") ?? "";
            if (!url || !title) {
                skippedNoUrl += 1;
                continue;
            }
            rows.push({
                title: escapeMarkdown(title),
                url: url.trim(),
                summary: escapeMarkdown(summary) || summariseBody(body) || "(no summary)",
                body: body.trim(),
            });
        }
    }
    finally {
        await session.close();
    }
    const indexLines = [];
    indexLines.push(`# ${escapeMarkdown(input.siteName)}`);
    indexLines.push("");
    if (input.siteDescription) {
        indexLines.push(`> ${escapeMarkdown(input.siteDescription)}`);
        indexLines.push("");
    }
    indexLines.push("## Pages");
    indexLines.push("");
    for (const row of rows) {
        indexLines.push(`- [${row.title}](${row.url}): ${row.summary}`);
    }
    indexLines.push("");
    indexLines.push("<!-- generated by @maxy/aeo-llms-txt-writer; spec: https://llmstxt.org/ -->");
    const llmsTxt = indexLines.join("\n");
    const fullLines = [];
    fullLines.push(`# ${escapeMarkdown(input.siteName)}`);
    fullLines.push("");
    if (input.siteDescription) {
        fullLines.push(`> ${escapeMarkdown(input.siteDescription)}`);
        fullLines.push("");
    }
    for (const row of rows) {
        fullLines.push(`# ${row.title}`);
        fullLines.push("");
        fullLines.push(`Source: ${row.url}`);
        fullLines.push("");
        if (row.body) {
            const safeBody = row.body.replace(HEADER_RX, "## ");
            fullLines.push(safeBody);
        }
        else {
            fullLines.push(row.summary);
        }
        fullLines.push("");
        fullLines.push("---");
        fullLines.push("");
    }
    const llmsFullTxt = fullLines.join("\n");
    const sizeBytes = {
        index: Buffer.byteLength(llmsTxt, "utf-8"),
        full: Buffer.byteLength(llmsFullTxt, "utf-8"),
    };
    process.stderr.write(`[aeo-llms-txt] site=${input.siteName} pages=${rows.length} skippedNoUrl=${skippedNoUrl} indexBytes=${sizeBytes.index} fullBytes=${sizeBytes.full}\n`);
    let writtenPaths;
    if (input.siteDir) {
        const dir = (0, node_path_1.resolve)(input.siteDir);
        let dirStat;
        try {
            dirStat = await (0, promises_1.stat)(dir);
        }
        catch (err) {
            const code = err?.code;
            throw new Error(`siteDir does not exist (${code ?? "unknown"}): ${dir}`);
        }
        if (!dirStat.isDirectory()) {
            throw new Error(`siteDir is not a directory: ${dir}`);
        }
        const indexPath = (0, node_path_1.resolve)(dir, "llms.txt");
        const fullPath = (0, node_path_1.resolve)(dir, "llms-full.txt");
        await (0, promises_1.writeFile)(indexPath, llmsTxt, "utf-8");
        await (0, promises_1.writeFile)(fullPath, llmsFullTxt, "utf-8");
        writtenPaths = { index: indexPath, full: fullPath };
        process.stderr.write(`[aeo-llms-txt] wrote site=${dir} indexBytes=${sizeBytes.index} fullBytes=${sizeBytes.full}\n`);
    }
    return {
        llmsTxt,
        llmsFullTxt,
        pageCount: rows.length,
        skippedNoUrl,
        sizeBytes,
        writtenPaths,
    };
}
//# sourceMappingURL=index.js.map