// Scratch timing driver for issue 39714 (not committed).
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { CheckpointRef } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import * as CheckpointStore from "./CheckpointStore.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as ServerConfig from "../config.ts";

const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
  prefix: "t3-capture-timing-",
});
const layerVcsProcess = VcsProcess.layer.pipe(
  Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);
const layerVcsDriver = VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess));
const layerTest = CheckpointStore.layer.pipe(
  Layer.provideMerge(layerVcsDriver),
  Layer.provideMerge(layerServerConfig),
  Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);

it.live(
    "times captureCheckpoint",
    () =>
      Effect.gen(function* () {
        const store = yield* CheckpointStore.CheckpointStore;
        const cwd = process.env.TIMING_REPO!;
        const runs = Number(process.env.TIMING_RUNS ?? "5");
        const label = process.env.TIMING_LABEL ?? "";
        const times: number[] = [];
        for (let i = 0; i < runs; i++) {
          const ref = CheckpointRef.make(`refs/t3/checkpoints/timing/${label}/${i}`);
          const start = process.hrtime.bigint();
          yield* store.captureCheckpoint({ cwd, checkpointRef: ref });
          times.push(Number(process.hrtime.bigint() - start) / 1e6);
          console.log(`RUN ${label} ${i} ${Math.round(times[i]!)}ms`);
        }
        const sorted = [...times].sort((a, b) => a - b);
        console.log(
          `TIMING ${label} runs=${JSON.stringify(times.map((t) => Math.round(t)))} median=${Math.round(sorted[Math.floor(sorted.length / 2)]!)} min=${Math.round(sorted[0]!)} max=${Math.round(sorted[sorted.length - 1]!)}`,
        );
      }).pipe(Effect.provide(layerTest)),
    3_000_000,
);
