// Scratch timing driver for #24895. Synthetic data only. Not committed.
// Usage: node driver.ts <worktree> <outDir>
const [worktree, outDir] = process.argv.slice(2);
if (!worktree || !outDir) throw new Error("usage: driver.ts <worktree> <outDir>");
const nm = `${worktree}/node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist`;
const Effect = await import(`${nm}/Effect.js`);
const Layer = await import(`${nm}/Layer.js`);
const SqlClient = await import(`${nm}/sql/SqlClient.js`);
const DateTime = await import(`${nm}/DateTime.js`);
const NodeServices = await import(
  (await import("node:module")).createRequire(`${worktree}/apps/server/package.json`).resolve(
    "@effect/platform-node/NodeServices",
  )
);
const brand = { make: (value: string) => value };
const Contracts = new Proxy({}, { get: () => brand }) as Record<string, typeof brand>;
const Sqlite = await import(`${worktree}/apps/server/src/persistence/Sqlite.ts`);
const ProjectionStore = await import(`${worktree}/apps/server/src/orchestration-v2/ProjectionStore.ts`);

const ACTIVE = Number(process.env.ACTIVE ?? 500);
const ARCHIVED = Number(process.env.ARCHIVED ?? 2000);
const RUNS = Number(process.env.RUNS ?? 2000);
const ITEMS_PER_RUN = Number(process.env.ITEMS_PER_RUN ?? 8);
const { EventId, MessageId, NodeId, ProjectId, ProviderDriverKind, ProviderInstanceId, RunId, RunAttemptId, ThreadId, TurnItemId } = Contracts;
const log = (...args: Array<unknown>) => console.log(new Date().toISOString(), ...args);

const program = Effect.gen(function* () {
  const store = yield* ProjectionStore.ProjectionStoreV2;
  const sql = yield* SqlClient.SqlClient;
  const now = new Date("2026-10-01T00:00:00Z");
  const at = DateTime.makeUnsafe(now);
  const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
  const projectId = ProjectId.make("project-synthetic");
  const createThread = (id: string, opts: { archived: boolean; branch: string | null }) =>
    store.apply({
      id: EventId.make(`event:${id}:created`),
      type: "thread.created",
      threadId: ThreadId.make(id),
      occurredAt: at,
      payload: {
        createdBy: "user", creationSource: "web", id: ThreadId.make(id), projectId, title: id,
        providerInstanceId: modelSelection.instanceId, modelSelection, runtimeMode: "full-access",
        interactionMode: "default", branch: opts.branch, worktreePath: null, activeProviderThreadId: null,
        lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
        forkedFrom: null, createdAt: at, updatedAt: at, archivedAt: opts.archived ? at : null,
        settledOverride: null, settledAt: null, lastVisitedAt: null, deletedAt: null,
      },
    });
  log("seeding threads");
  yield* sql.withTransaction(
    Effect.forEach(Array.from({ length: ACTIVE }, (_, i) => i), (i) =>
      createThread(`active-${i}`, { archived: false, branch: `feature/${i}` }), { discard: true }),
  );
  yield* sql.withTransaction(
    Effect.forEach(Array.from({ length: ARCHIVED }, (_, i) => i), (i) =>
      createThread(`archived-${i}`, { archived: true, branch: `old/${i}` }), { discard: true }),
  );
  const bigPullRequests = JSON.stringify(
    Array.from({ length: 40 }, (_, n) => ({ projectId, repository: "acme/project", number: n, url: `https://github.com/acme/project/pull/${n}`, title: "x".repeat(400) })),
  );
  yield* sql`UPDATE orchestration_v2_projection_threads
    SET payload_json = json_set(payload_json, '$.pullRequests', json(${bigPullRequests}))
    WHERE thread_id LIKE 'archived-%'`;
  const big = ThreadId.make("active-0");
  log("seeding runs", RUNS, "items", RUNS * ITEMS_PER_RUN);
  for (let base = 0; base < RUNS; base += 200) {
    yield* sql.withTransaction(
      Effect.forEach(Array.from({ length: Math.min(200, RUNS - base) }, (_, k) => base + k), (r) =>
        Effect.gen(function* () {
          const runId = RunId.make(`run-${r}`);
          const nodeId = NodeId.make(`node-${r}`);
          const last = r === RUNS - 1;
          yield* store.apply({
            id: EventId.make(`event:run-${r}`), type: "run.created", threadId: big, runId, nodeId,
            driver: ProviderDriverKind.make("codex"), occurredAt: at,
            payload: {
              id: runId, threadId: big, ordinal: r + 1, providerInstanceId: modelSelection.instanceId,
              modelSelection, providerThreadId: null, userMessageId: MessageId.make(`msg-${r}`),
              rootNodeId: nodeId, activeAttemptId: last ? RunAttemptId.make("attempt-last") : null,
              status: last ? "running" : "completed", requestedAt: at, startedAt: at,
              completedAt: last ? null : at, checkpointId: null, contextHandoffId: null,
            },
          });
          for (let k = 0; k < ITEMS_PER_RUN; k++) {
            yield* store.apply({
              id: EventId.make(`event:item-${r}-${k}`), type: "turn-item.updated", threadId: big, runId, occurredAt: at,
              payload: {
                id: TurnItemId.make(`item-${r}-${k}`), threadId: big, runId, nodeId: null, providerThreadId: null,
                providerTurnId: null, nativeItemRef: null, parentItemId: null, ordinal: r * ITEMS_PER_RUN + k + 1,
                status: "completed", title: null, startedAt: at, completedAt: at, updatedAt: at,
                type: "assistant_message", messageId: MessageId.make(`msg-${r}-${k}`),
                text: "lorem ipsum ".repeat(200), streaming: false,
              },
            });
          }
        }), { discard: true }),
    );
  }
  log("seeded");
  const time = <A, E, R>(label: string, effect: Effect.Effect<A, E, R>, describe: (a: A) => string) =>
    Effect.gen(function* () {
      const results: Array<number> = [];
      let last: A | undefined;
      for (let i = 0; i < 5; i++) {
        const start = performance.now();
        last = yield* effect;
        results.push(performance.now() - start);
      }
      log(`${label}: ms per call [${results.map((ms) => ms.toFixed(1)).join(", ")}] ${describe(last as A)}`);
    });
  yield* time(
    "(a) main sweep read getShellSnapshot(active, unsettledOnly)",
    store.getShellSnapshot({ location: "active", unsettledOnly: true }),
    (s) => `threads=${s.threads.length}`,
  );
  yield* time(
    "(a') payload-only read: active thread payload_json + MAX(sequence)",
    sql.withTransaction(Effect.all([
      sql`SELECT payload_json FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.archivedAt') IS NULL`,
      sql`SELECT MAX(sequence) AS s FROM orchestration_events WHERE application_event_version = 2 AND aggregate_kind = 'thread'`,
    ])),
    ([rows]) => `threads=${rows.length}`,
  );
  yield* time(
    "(b) main run-status check getRuntimeRecoveryProjection(thread with runs)",
    store.getRuntimeRecoveryProjection(big),
    (p) => `runs=${p.runs.length} turnItems=${p.turnItems.length}`,
  );
  yield* time(
    "(b') primary-key read of one run",
    sql`SELECT payload_json FROM orchestration_v2_projection_runs WHERE run_id = ${`run-${RUNS - 1}`}`,
    (rows) => `rows=${rows.length}`,
  );
  yield* time(
    "(c) fixed sweep read getPullRequestSyncSnapshot(active, unsettledOnly)",
    store.getPullRequestSyncSnapshot({ location: "active", unsettledOnly: true }),
    (s) => `threads=${s.threads.length} sequence=${s.snapshotSequence}`,
  );
  yield* time(
    "(c') fixed single-thread read getPullRequestSyncSnapshot(threadIds=[big])",
    store.getPullRequestSyncSnapshot({ threadIds: [big] }),
    (s) => `threads=${s.threads.length}`,
  );
  yield* time(
    "(d) fixed run-status check getRun(thread with runs, last run)",
    store.getRun(big, RunId.make(`run-${RUNS - 1}`)),
    (run) => `status=${run?.status} activeAttemptId=${run?.activeAttemptId}`,
  );
});

const dbPath = `${outDir}/synthetic.sqlite`;
await Effect.runPromise(
  program.pipe(
    Effect.provide(
      ProjectionStore.layer.pipe(
        Layer.provideMerge(Sqlite.layerFromPath(dbPath)),
        Layer.provideMerge(NodeServices.layer),
      ),
    ),
    Effect.scoped,
  ),
);
