// Scratch measurement for #40314: 6 selected-file commits through the real GitVcsDriverCore on a
// files-backend clone of the t3code checkout. Writes per-commit span timings to PERF_OUT.
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Tracer from "effect/Tracer";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as ServerConfig from "../config.ts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";

const layerTest = GitVcsDriver.layer.pipe(
  Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-perf-40314-" })),
  Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);

const sh = (cwd: string, args: string[]) =>
  NodeChildProcess.execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 1 << 28 }).trim();

it.live("partial commits", () =>
    Effect.gen(function* () {
      const source = process.env.PERF_SOURCE!;
      const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "perf40314-"));
      const repo = NodePath.join(root, "p0");
      sh(root, ["clone", "-q", "--local", source, repo]);
      sh(repo, ["config", "user.name", "Perf"]);
      sh(repo, ["config", "user.email", "perf@example.com"]);
      sh(repo, ["checkout", "-q", "-B", "work"]);
      const refFormat = sh(repo, ["rev-parse", "--show-ref-format"]);
      const tracked = sh(repo, ["ls-files"]).split("\n").length;

      const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
      let spawns = 0;
      const spawner = ChildProcessSpawner.make((command) => {
        if (ChildProcess.isStandardCommand(command)) spawns++;
        return delegate.spawn(command);
      });
      const driver = yield* makeGitVcsDriverCore().pipe(
        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
      );
      const spans: Array<Tracer.NativeSpan> = [];
      const tracer = Tracer.make({
        span: (options) => {
          const span = new Tracer.NativeSpan(options);
          spans.push(span);
          return span;
        },
      });

      const runs = [];
      for (let i = 0; i < 6; i++) {
        for (const f of ["README.md", "package.json", "AGENTS.md"])
          NodeFS.appendFileSync(NodePath.join(repo, f), `\ncommit ${i} ${Date.now()}\n`);
        spans.length = 0;
        spawns = 0;
        const t0 = performance.now();
        yield* driver
          .commit(repo, `perf commit ${i}`, "", { stage: { filePaths: ["README.md"] } })
          .pipe(Effect.withTracer(tracer));
        const totalMs = Math.round(performance.now() - t0);
        const ms = (s: Tracer.NativeSpan) =>
          s.status._tag === "Ended"
            ? Number(s.status.endTime - s.status.startTime) / 1e6
            : Number.NaN;
        const commitSpans = spans
          .filter((s) => s.name.startsWith("GitVcsDriver.commit"))
          .map((s) => ({ name: s.name, ms: Math.round(ms(s)) }));
        const operationRef = commitSpans.filter((s) => s.name === "GitVcsDriver.commit.operationRef");
        runs.push({
          run: i,
          totalMs,
          gitSpawns: spawns,
          operationRefCount: operationRef.length,
          operationRefMs: operationRef.reduce((a, s) => a + s.ms, 0),
          commitSpans,
        });
      }
      NodeFS.writeFileSync(
        process.env.PERF_OUT!,
        JSON.stringify({ refFormat, tracked, head: sh(source, ["rev-parse", "HEAD"]), runs }, null, 2),
      );
    }).pipe(Effect.provide(layerTest)),
);
