import { getSession } from "../lib/neo4j.js";
import { restoreNode } from "../../../../../lib/graph-trash/dist/index.js";
import { withWriteEvent } from "../lib/log-ingest.js";
export async function memoryRestore(params) {
    return withWriteEvent({ tool: "memory-restore", accountId: params.accountId }, () => memoryRestoreImpl(params), (r) => ({ elementId: r.elementId, labels: r.labels }));
}
async function memoryRestoreImpl(params) {
    const { accountId, elementId } = params;
    const session = getSession();
    try {
        const root = await restoreNode({ session, accountId, elementId });
        let sections = 0;
        let chunks = 0;
        // Both :KnowledgeDocument (document path) and :ConversationArchive
        // (conversation path — Task 397) own :Section/:Chunk children; revival
        // cascade is identical for both parent labels.
        if (root.labels.includes("KnowledgeDocument") || root.labels.includes("ConversationArchive")) {
            const childResult = await session.run(`MATCH (d) WHERE elementId(d) = $eid
         OPTIONAL MATCH (d)-[:HAS_SECTION]->(s:Section)
         WHERE s:Trashed
         OPTIONAL MATCH (s)-[:HAS_CHUNK]->(c:Chunk)
         WHERE c:Trashed
         WITH collect(DISTINCT s) AS sections, collect(DISTINCT c) AS chunks
         RETURN [s IN sections WHERE s IS NOT NULL | elementId(s)] AS sectionIds,
                [c IN chunks   WHERE c IS NOT NULL | elementId(c)] AS chunkIds`, { eid: elementId });
            const sectionIds = childResult.records[0]?.get("sectionIds") ?? [];
            const chunkIds = childResult.records[0]?.get("chunkIds") ?? [];
            for (const sid of sectionIds) {
                await restoreNode({ session, accountId, elementId: sid });
                sections++;
            }
            for (const cid of chunkIds) {
                await restoreNode({ session, accountId, elementId: cid });
                chunks++;
            }
        }
        return {
            elementId,
            labels: root.labels,
            cascade: { sections, chunks },
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=memory-restore.js.map