/**
 * One-shot backfill of the typed-edge pass over every existing prose-bearing
 * node for the current account. Idempotent — MERGE handles re-runs cleanly,
 * so a second invocation accepts zero edges.
 *
 * Usage (admin-agent invokable via Bash):
 *   cd platform/plugins/memory/mcp
 *   node --loader ts-node/esm scripts/backfill-typed-edges.ts
 *
 * Reads ACCOUNT_ID from env (same convention as the MCP server). Loops
 * `runTypedEdgePass` with `sinceIso: null` in 500-node pages until the
 * page returns 0 nodes (exhausted). Logs per-batch progress with
 * `[typed-edge-pass:backfill]`.
 */

import { getSession, closeDriver } from "../src/lib/neo4j.js";
import { runTypedEdgePass } from "../src/lib/typed-edge-pass.js";

const PAGE_SIZE = 500;

async function main(): Promise<void> {
  const accountId = process.env.ACCOUNT_ID;
  if (!accountId) {
    console.error("ACCOUNT_ID env var is required");
    process.exit(1);
  }

  let batch = 0;
  let totalNodes = 0;
  let totalAccepted = 0;
  let totalRejected = 0;
  let totalFailed = 0;

  while (true) {
    const session = getSession();
    try {
      const result = await runTypedEdgePass({
        session,
        accountId,
        sinceIso: null,
        sessionId: null,
        maxNodes: PAGE_SIZE,
      });
      batch += 1;
      totalNodes += result.nodes;
      totalAccepted += result.accepted;
      totalRejected += result.rejected;
      totalFailed += result.failed;
      console.log(
        `[typed-edge-pass:backfill] batch=${batch} done=${totalNodes} accepted=${result.accepted} rejected=${result.rejected} failed=${result.failed} ms=${result.ms}`,
      );
      if (result.nodes < PAGE_SIZE || result.accepted === 0) {
        // Exhausted: either the page came back short, or a re-run page
        // produced no new accepted edges (idempotency convergence).
        break;
      }
    } finally {
      await session.close();
    }
  }

  console.log(
    `[typed-edge-pass:backfill] complete batches=${batch} totalNodes=${totalNodes} totalAccepted=${totalAccepted} totalRejected=${totalRejected} totalFailed=${totalFailed}`,
  );
  await closeDriver();
}

main().catch(async (err) => {
  console.error(`[typed-edge-pass:backfill] error: ${err instanceof Error ? err.message : String(err)}`);
  await closeDriver();
  process.exit(1);
});
