import { getSession } from "../lib/neo4j.js";
import { decideGate, writeClassifyTempFile, buildDispatchEnvelope, } from "../lib/kd-classify-gate.js";
async function readKd(accountId, attachmentId) {
    const session = getSession();
    try {
        const result = await session.run(`MATCH (kd:KnowledgeDocument { accountId: $accountId, attachmentId: $attachmentId })
       RETURN kd.source AS source,
              coalesce(size(kd.body), 0) AS bodyLen,
              coalesce(kd.lastClassifiedBodyLength, 0) AS lastLen,
              kd.body AS body`, { accountId, attachmentId });
        if (result.records.length === 0)
            return null;
        const r = result.records[0];
        return {
            source: r.get("source"),
            bodyLen: Number(r.get("bodyLen")),
            lastClassifiedBodyLength: Number(r.get("lastLen")),
        };
    }
    finally {
        await session.close();
    }
}
async function readKdBody(accountId, attachmentId) {
    const session = getSession();
    try {
        const result = await session.run(`MATCH (kd:KnowledgeDocument { accountId: $accountId, attachmentId: $attachmentId })
       RETURN kd.body AS body`, { accountId, attachmentId });
        if (result.records.length === 0)
            return null;
        return result.records[0].get("body") ?? null;
    }
    finally {
        await session.close();
    }
}
export async function kdClassify(params) {
    const { accountId, attachmentId } = params;
    const meta = await readKd(accountId, attachmentId);
    if (!meta) {
        throw new Error(`kd-classify: no :KnowledgeDocument with attachmentId=${attachmentId} in account ${accountId}.`);
    }
    if (meta.bodyLen === 0) {
        throw new Error(`kd-classify: :KnowledgeDocument ${attachmentId} has no body; cannot classify. (Bodyless KDs — e.g. PDF/attachment — do not support the reclassify-gate flow.)`);
    }
    const decision = decideGate({
        bodyLen: meta.bodyLen,
        lastClassifiedBodyLength: meta.lastClassifiedBodyLength,
    });
    process.stderr.write(`[kd-classify] attachmentId=${attachmentId.slice(0, 12)} source=${meta.source ?? "unknown"} bodyLen=${meta.bodyLen} lastLen=${meta.lastClassifiedBodyLength} growthPct=${decision.growthPct.toFixed(3)} action=${decision.action}\n`);
    if (decision.action === "skip") {
        return decision.reason ?? "no classification needed";
    }
    const body = await readKdBody(accountId, attachmentId);
    if (body === null || body.length === 0) {
        // Race: body emptied between the two reads. Unexpected; surface loudly.
        throw new Error(`kd-classify: body for ${attachmentId} was readable in the metadata query but is now empty.`);
    }
    const accountDir = process.env.ACCOUNT_DIR;
    if (!accountDir) {
        throw new Error(`kd-classify: ACCOUNT_DIR env not set; cannot stage body for librarian dispatch.`);
    }
    const tempFilePath = await writeClassifyTempFile(accountDir, attachmentId, body);
    return buildDispatchEnvelope({
        attachmentId,
        source: meta.source ?? "unknown",
        tempFilePath,
        bodyLen: meta.bodyLen,
        lastClassifiedBodyLength: meta.lastClassifiedBodyLength,
        growthPct: decision.growthPct,
    });
}
//# sourceMappingURL=kd-classify.js.map