import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as VcsProcess from "./src/vcs/VcsProcess.ts";

const READS = Number(process.env.READS ?? 9);
const BG = Number(process.env.BG ?? 6);
const cwd = process.env.PROBE_CWD!;
const project = "gitlab-org%2Fcli";
const issues = [8827, 8824, 8823, 8822, 8821, 8820, 8819, 8818, 8817, 8816];

const spawnAt = new Map<string, number>();
(globalThis as any).__probeSpawn = (input: { env?: Record<string, string> }) => {
  const tag = input.env?.PROBE_TAG;
  if (tag) spawnAt.set(tag, performance.now());
};

let seq = 0;
const glab = (path: string, background: boolean) => {
  const tag = String(seq++);
  const requested = performance.now();
  return Effect.gen(function* () {
    const vcs = yield* VcsProcess.VcsProcess;
    yield* vcs.run({
      operation: "GitLabCli.execute",
      command: "glab",
      args: ["api", path],
      cwd,
      env: { GITLAB_HOST: "gitlab.com", PROBE_TAG: tag },
      timeoutMs: 60_000,
    });
    const done = performance.now();
    return { wait: (spawnAt.get(tag) ?? done) - requested, total: done - requested };
  }).pipe(Effect.provideService(VcsProcess.Background, background));
};

const program = Effect.gen(function* () {
  const bg = yield* Effect.forEach(
    Array.from({ length: BG }, (_, i) => i),
    (i) =>
      Effect.forever(
        Effect.suspend(() => glab(`projects/${project}/merge_requests/${2400 + ((seq * 7 + i) % 200)}`, true)).pipe(
          Effect.ignore,
          Effect.andThen(Effect.sleep(`${Number(process.env.BG_GAP_MS ?? 1000)} millis`)),
        ),
      ).pipe(Effect.forkChild),
  );
  yield* Effect.sleep("3 seconds");
  const rows: Array<{ wait: number; total: number }> = [];
  for (let r = 0; r < READS; r++) {
    const iid = issues[r % issues.length];
    const base = `projects/${project}/issues/${iid}`;
    const start = performance.now();
    const parts = yield* Effect.all(
      [
        glab(base, false),
        glab(`${base}/notes?per_page=100&page=1`, false),
        glab(`${base}/closed_by?per_page=100&page=1`, false),
        glab(`${base}/related_merge_requests?per_page=100&page=1`, false),
      ],
      { concurrency: "unbounded" },
    );
    rows.push({ wait: Math.max(...parts.map((p) => p.wait)), total: performance.now() - start });
    yield* Effect.sleep("500 millis");
  }
  yield* Fiber.interruptAll(bg);
  console.log(JSON.stringify({ limit: process.env.T3_PROBE_NON_GIT ?? "4(default)", bg: BG, rows }));
});

Effect.runPromise(
  program.pipe(Effect.provide(VcsProcess.layer.pipe(Layer.provide(NodeServices.layer)))),
).then(
  () => process.exit(0),
  (e) => {
    console.error(e);
    process.exit(1);
  },
);
