import { getSession } from "../lib/neo4j.js";
import { buildJsonLd, renderJsonLdScript, MissingPropertyError, } from "../lib/schema-mapping.js";
function isPropertyBag(v) {
    return typeof v === "object" && v !== null && !Array.isArray(v);
}
export async function emitJsonLd(input) {
    if (!input.entityId && !input.label) {
        throw new Error("aeo-emit-jsonld requires either entityId or label+properties");
    }
    if (input.entityId) {
        const session = getSession();
        try {
            const r = await session.run(`MATCH (n) WHERE elementId(n) = $id AND n.accountId = $accountId
         RETURN labels(n) AS labels, properties(n) AS props, elementId(n) AS id LIMIT 1`, { id: input.entityId, accountId: input.accountId });
            if (r.records.length === 0) {
                throw new Error(`aeo-emit-jsonld: no node with elementId=${input.entityId} in account=${input.accountId}`);
            }
            const rec = r.records[0];
            const labels = rec.get("labels");
            const props = rec.get("props");
            const id = rec.get("id");
            const primaryLabel = labels.find((l) => l !== "Resource") ?? labels[0];
            const obj = buildJsonLd({
                label: primaryLabel,
                elementId: id,
                properties: props,
            });
            process.stderr.write(`[aeo-emit-jsonld] entityId=${id} schemaType=${obj["@type"]} source=graph\n`);
            return {
                jsonLd: obj,
                scriptBlock: renderJsonLdScript(obj),
                schemaType: obj["@type"],
                source: "graph",
            };
        }
        finally {
            await session.close();
        }
    }
    if (!input.label || !isPropertyBag(input.properties)) {
        throw new Error("aeo-emit-jsonld: label requires a properties object");
    }
    const obj = buildJsonLd({
        label: input.label,
        properties: input.properties,
    });
    process.stderr.write(`[aeo-emit-jsonld] label=${input.label} schemaType=${obj["@type"]} source=inline\n`);
    return {
        jsonLd: obj,
        scriptBlock: renderJsonLdScript(obj),
        schemaType: obj["@type"],
        source: "inline",
    };
}
export { MissingPropertyError };
//# sourceMappingURL=aeo-emit-jsonld.js.map