// Scratch measurement for issue 46357 (not committed).
// node --expose-gc apps/server/scratch-catchup-heap.ts <totalEvents>
import { EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";

import * as Sqlite from "./src/persistence/Sqlite.ts";
import * as EventSink from "./src/orchestration-v2/EventSink.ts";
import * as EventStore from "./src/orchestration-v2/EventStore.ts";
import * as ProjectionStore from "./src/orchestration-v2/ProjectionStore.ts";

const TOTAL = Number(process.argv[2] ?? 40_000);
const BATCH = 500;

const layer = EventSink.layer.pipe(
  Layer.provideMerge(
    Layer.merge(
      EventStore.layer,
      ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest)),
    ),
  ),
  Layer.provide(Sqlite.layerMemory),
);

const heapMb = () => {
  (globalThis as any).gc();
  (globalThis as any).gc();
  return Math.round(process.memoryUsage().heapUsed / 2 ** 20);
};

const program = Effect.gen(function* () {
  const store = yield* EventStore.EventStoreV2;
  const sink = yield* EventSink.EventSinkV2;
  const now = yield* DateTime.now;
  const providerInstanceId = ProviderInstanceId.make("codex");
  for (let start = 0; start < TOTAL; start += BATCH) {
    const events = Array.from({ length: Math.min(BATCH, TOTAL - start) }, (_, k) => {
      const i = start + k;
      const id = ThreadId.make(`t-${i}`);
      return {
        id: EventId.make(`e-${i}`),
        type: "thread.created" as const,
        threadId: id,
        occurredAt: now,
        payload: {
          id,
          projectId: ProjectId.make("project"),
          title: `synthetic ${i} ` + "x".repeat(1000),
          createdBy: "user" as const,
          creationSource: "web" as const,
          providerInstanceId,
          modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
          runtimeMode: "full-access" as const,
          interactionMode: "default" as const,
          branch: null,
          worktreePath: null,
          activeProviderThreadId: null,
          lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
          forkedFrom: null,
          createdAt: now,
          updatedAt: now,
          archivedAt: null,
          deletedAt: null,
          settledOverride: null,
          settledAt: null,
          snoozedUntil: null,
          snoozedAt: null,
          lastVisitedAt: null,
        },
      };
    });
    yield* store.append({ events });
  }
  const base = heapMb();
  let seen = 0;
  const fractions = [0.25, 0.5, 0.75, 1];
  let next = 0;
  const samples: Array<string> = [];
  // Unbounded stream() from sequence 0, like the old ThreadHandoff caller; the live tail never ends.
  yield* sink.stream().pipe(
    Stream.runForEach(() =>
      Effect.sync(() => {
        seen++;
        while (next < fractions.length && seen >= TOTAL * fractions[next]!) {
          samples.push(`${seen}/${TOTAL} replayed: live heap growth after GC ${heapMb() - base} MB`);
          next++;
        }
      }),
    ),
    Effect.forkChild,
  );
  while (next < fractions.length) yield* Effect.sleep("50 millis");
  for (const s of samples) console.log(s);
});

await Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(layer)) as any);
process.exit(0);
