import { getSession } from "../lib/neo4j.js";
import { memoryUpdate } from "./memory-update.js";
import { notTrashed } from "../../../../../lib/graph-trash/dist/index.js";
const MAX_AMBIGUOUS_CANDIDATES_SURFACED = 5;
export async function memoryUpdateByName(params) {
    const { label, name, accountId, properties, createdBy } = params;
    if (!label.trim())
        throw new Error("label is required");
    if (!name.trim())
        throw new Error("name is required");
    if (Object.keys(properties).length === 0) {
        throw new Error("properties is required — at least one property must be provided");
    }
    const session = getSession();
    let elementId;
    try {
        const result = await session.run(`MATCH (n:\`${label}\` { accountId: $accountId, name: $name })
       WHERE ${notTrashed("n")}
       RETURN elementId(n) AS nodeId
       LIMIT ${MAX_AMBIGUOUS_CANDIDATES_SURFACED + 1}`, { accountId, name });
        const matches = result.records.map((r) => r.get("nodeId"));
        if (matches.length === 0) {
            throw new Error(`memory-update-by-name: no :${label} found with name=${JSON.stringify(name)} ` +
                `under accountId=${accountId.slice(0, 8)} (trashed nodes excluded). ` +
                `Confirm the label and name match an existing node — try memory-search with labels:["${label}"] and query:${JSON.stringify(name)} first.`);
        }
        if (matches.length > 1) {
            const surfaced = matches.slice(0, MAX_AMBIGUOUS_CANDIDATES_SURFACED);
            const tail = matches.length > MAX_AMBIGUOUS_CANDIDATES_SURFACED ? ` (and ${matches.length - MAX_AMBIGUOUS_CANDIDATES_SURFACED} more)` : "";
            throw new Error(`memory-update-by-name: ambiguous — ${matches.length} :${label} rows share name=${JSON.stringify(name)} under this account. ` +
                `Pick one elementId and call memory-update directly. Candidates: ${surfaced.join(", ")}${tail}.`);
        }
        elementId = matches[0];
    }
    finally {
        await session.close();
    }
    // Delegate to the canonical update path — embedding refresh, write gates,
    // compiled-truth refusal, restricted-key strip, and provenance stamping
    // all live there. memory-update-by-name owns only the lookup; it never
    // duplicates the write logic.
    const updated = await memoryUpdate({ nodeId: elementId, properties, accountId, createdBy });
    return { nodeId: updated.nodeId, labels: updated.labels };
}
//# sourceMappingURL=memory-update-by-name.js.map