// Scratch benchmark for issue 40987. Not committed.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
// @effect-diagnostics-next-line nodeBuiltinImport:off
import * as fs from "node:fs";
// @effect-diagnostics-next-line nodeBuiltinImport:off
import * as path from "node:path";

import * as ServerConfig from "../config.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import { checkRequestDpopProof, verifyRequestDpopProof } from "./dpop.ts";
import { makeDpopKey } from "./dpop.testkit.ts";

const RUNS = Number(process.env.BENCH_RUNS ?? 40);
const LOAD = process.env.BENCH_LOAD ?? "none"; // none | pool
const OUT = process.env.BENCH_OUT ?? "/tmp/bench.json";
const LOAD_DIR = process.env.BENCH_LOAD_DIR ?? "/tmp";

const layer = Layer.mergeAll(
  ServerSecretStore.layer.pipe(
    Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-bench-40987-" })),
  ),
).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));

// Keeps 8 fs ops in flight (twice the libuv pool), each a 4 MiB write + fsync,
// like other server work (sqlite, git, file reads) competing for the same pool.
const startPoolLoad = () => {
  let stopped = false;
  const buf = Buffer.alloc(4 * 1024 * 1024, 1);
  const worker = async (i: number) => {
    const p = path.join(LOAD_DIR, `load-${i}.bin`);
    while (!stopped) {
      const fh = await fs.promises.open(p, "w");
      await fh.write(buf);
      await fh.sync();
      await fh.close();
    }
    await fs.promises.rm(p, { force: true });
  };
  const all = Array.from({ length: 8 }, (_, i) => worker(i));
  return async () => {
    stopped = true;
    await Promise.all(all);
  };
};

const pct = (xs: number[], p: number) => {
  const s = [...xs].sort((a, b) => a - b);
  return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!;
};

it.live("bench", () =>
  Effect.gen(function* () {
    const key = makeDpopKey();
    const url = "http://127.0.0.1/api/voice/cloud/keys";
    const token = "session-token";
    const stop = LOAD === "pool" ? startPoolLoad() : undefined;
    yield* Effect.promise(() => new Promise((r) => setTimeout(r, 500)));
    const check: number[] = [];
    const verify: number[] = [];
    for (let i = 0; i < RUNS; i++) {
      for (const [kind, arr] of [
        ["check", check],
        ["verify", verify],
      ] as const) {
        const iat = Math.floor(Date.now() / 1000);
        const request = HttpServerRequest.fromWeb(
          new Request(url, {
            headers: { host: "127.0.0.1", dpop: key.sign({ method: "GET", url, token, iat }) },
          }),
        );
        const input = { request, expectedThumbprint: key.thumbprint, expectedAccessToken: token };
        const t0 = performance.now();
        if (kind === "check") yield* checkRequestDpopProof(input);
        else yield* verifyRequestDpopProof(input);
        arr.push(performance.now() - t0);
      }
    }
    if (stop) yield* Effect.promise(() => stop());
    const sum = (xs: number[]) => ({
      runs: xs.length,
      median: pct(xs, 50),
      p90: pct(xs, 90),
      min: Math.min(...xs),
      max: Math.max(...xs),
    });
    const res = { load: LOAD, check: sum(check), verify: sum(verify), raw: { check, verify } };
    fs.writeFileSync(OUT, JSON.stringify(res, null, 2));
    console.log(JSON.stringify({ load: LOAD, check: res.check, verify: res.verify }));
  }).pipe(Effect.provide(layer)),
);
