// Scratch benchmark for #38792; not committed.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/sql/SqlClient";

import * as SqlitePersistence from "./persistence/Sqlite.ts";
import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";

const dbPath = process.argv[2]!;
const runs = Number(process.argv[3] ?? 5);

const time = <A, E, R>(label: string, effect: Effect.Effect<A, E, R>, size: (a: A) => number) =>
  Effect.gen(function* () {
    const results: number[] = [];
    let n = 0;
    for (let i = 0; i < runs; i++) {
      const start = performance.now();
      const value = yield* effect;
      results.push(performance.now() - start);
      n = size(value);
    }
    const sorted = [...results].sort((a, b) => a - b);
    console.log(
      JSON.stringify({
        label,
        threads: n,
        runsMs: results.map(Math.round),
        medianMs: Math.round(sorted[Math.floor(sorted.length / 2)]!),
        minMs: Math.round(sorted[0]!),
        maxMs: Math.round(sorted.at(-1)!),
      }),
    );
  });

const program = Effect.gen(function* () {
  const store = yield* ProjectionStore.ProjectionStoreV2;
  const sql = yield* SqlClient.SqlClient;
  yield* time(
    "getShellSnapshot() as StorageCleanup.readThreads calls it",
    store.getShellSnapshot(),
    (s) => s.threads.length + s.archivedThreads.length,
  );
  yield* time(
    "getShellSnapshot({ location: 'active' })",
    store.getShellSnapshot({ location: "active" }),
    (s) => s.threads.length,
  );
  // Only what cleanup reads: identity, worktree, lineage, settlement fields and the latest run.
  yield* time(
    "narrow read of the fields cleanup uses",
    sql`
      SELECT
        t.thread_id, t.project_id, t.archived_at, t.updated_at,
        json_extract(t.payload_json, '$.worktreePath') AS worktree_path,
        json_extract(t.payload_json, '$.branch') AS branch,
        json_extract(t.payload_json, '$.lineage') AS lineage,
        json_extract(t.payload_json, '$.settledOverride') AS settled_override,
        json_extract(t.payload_json, '$.settledAt') AS settled_at,
        latest.run_id, latest.status, latest.requested_at, latest.completed_at
      FROM orchestration_v2_projection_threads t
      LEFT JOIN orchestration_v2_projection_runs latest ON latest.run_id = (
        SELECT r.run_id FROM orchestration_v2_projection_runs r
        WHERE r.thread_id = t.thread_id ORDER BY r.ordinal DESC LIMIT 1
      )
      WHERE t.deleted_at IS NULL
    `,
    (rows) => rows.length,
  );
});

program.pipe(
  Effect.provide(
    ProjectionStore.layer.pipe(
      Layer.provideMerge(SqlitePersistence.layerFromPath(dbPath)),
      Layer.provideMerge(NodeServices.layer),
    ),
  ),
  Effect.runPromise,
);
