import { randomUUID } from "node:crypto";
import { auditHtml } from "../lib/audit-heuristics.js";
import { getSession } from "../lib/neo4j.js";
async function fetchHtml(url) {
    const res = await fetch(url, {
        redirect: "follow",
        headers: { "User-Agent": "maxy-aeo-audit/0.1" },
    });
    if (!res.ok) {
        throw new Error(`aeo-audit-page: GET ${url} returned HTTP ${res.status}`);
    }
    return await res.text();
}
export async function auditPage(input) {
    if (!input.url && !input.html) {
        throw new Error("aeo-audit-page requires one of url or html");
    }
    if (input.url && input.html) {
        throw new Error("aeo-audit-page: pass exactly one of url or html, not both");
    }
    const html = input.html ?? (await fetchHtml(input.url));
    const target = input.url ?? "(inline html)";
    const result = auditHtml(html);
    const runAt = new Date().toISOString();
    const fails = result.heuristics
        .filter((h) => h.status === "fail")
        .map((h) => h.name);
    const warns = result.heuristics
        .filter((h) => h.status === "warn")
        .map((h) => h.name);
    process.stderr.write(`[aeo-audit] target=${target} score=${result.score} fails=${fails.join(",") || "-"} warns=${warns.join(",") || "-"}\n`);
    let elementId;
    if (input.persist) {
        const auditId = randomUUID();
        const session = getSession();
        try {
            const r = await session.run(`CREATE (a:AEOAudit {
           accountId: $accountId,
           auditId: $auditId,
           target: $target,
           score: $score,
           heuristicsJson: $heuristicsJson,
           runAt: $runAt,
           createdByAgent: $agent,
           createdBySession: $session,
           createdAt: $runAt
         })
         WITH a
         OPTIONAL MATCH (d:KnowledgeDocument)
           WHERE elementId(d) = $kdocId AND d.accountId = $accountId
         FOREACH (_ IN CASE WHEN d IS NULL THEN [] ELSE [1] END |
           MERGE (d)-[:HAS_AEO_AUDIT]->(a)
         )
         RETURN elementId(a) AS id`, {
                accountId: input.accountId,
                auditId,
                target,
                score: result.score,
                heuristicsJson: JSON.stringify(result.heuristics),
                runAt,
                agent: input.agentSlug ?? "system",
                session: input.sessionId ?? null,
                kdocId: input.targetKnowledgeDocumentId ?? null,
            });
            elementId = r.records[0]?.get("id");
            process.stderr.write(`[aeo-audit] persisted auditId=${auditId} elementId=${elementId ?? "-"}\n`);
        }
        finally {
            await session.close();
        }
    }
    return {
        ...result,
        target,
        audit: { elementId, runAt },
    };
}
//# sourceMappingURL=aeo-audit-page.js.map