// Evidence driver for PR #23624. Scratch file: copied byte-identically into each checkout, never committed.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import * as nfs from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import { assert, it } from "@effect/vitest";

import { CheckpointRef } from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";

const layerServerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-ev23624-" });
const layerGitContract = Layer.mergeAll(GitVcsDriver.layerVcs, GitVcsDriver.layer).pipe(
  Layer.provide(layerServerConfig),
  Layer.provideMerge(VcsProcess.layer),
  Layer.provideMerge(NodeServices.layer),
);

const SIDE = process.env.EV_SIDE ?? "unknown";
const OUT_DIR = "/tmp/ev-23624/cap";
const OUT = `${OUT_DIR}/results-${SIDE}.jsonl`;
const REPOS = `${OUT_DIR}/repos-${SIDE}`;
nfs.mkdirSync(REPOS, { recursive: true });
nfs.writeFileSync(OUT, "");

// testUtils/gitConfig.setup.ts exports core.filemode=false to every git child, which hides
// the chmod rows (R2). Append core.filemode=true, Git's default on Linux; later entries win.
{
  const count = Number(process.env.GIT_CONFIG_COUNT ?? "0");
  process.env.GIT_CONFIG_COUNT = String(count + 1);
  process.env[`GIT_CONFIG_KEY_${count}`] = "core.filemode";
  process.env[`GIT_CONFIG_VALUE_${count}`] = "true";
}

const T = 1_700_000_000;
const ENV = { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null" };
const git = (cwd: string, args: ReadonlyArray<string>, input?: string | Buffer): Buffer =>
  execFileSync("git", args, {
    cwd,
    env: ENV,
    input,
    maxBuffer: 1 << 30,
    stdio: ["pipe", "pipe", "pipe"],
  });
const gits = (cwd: string, args: ReadonlyArray<string>, input?: string | Buffer) =>
  git(cwd, args, input).toString("utf8");
const sha = (file: string | Buffer) =>
  nfs.existsSync(file) ? createHash("sha256").update(nfs.readFileSync(file)).digest("hex") : "missing";
const join = (a: string, b: string | Buffer) =>
  typeof b === "string" ? `${a}/${b}` : Buffer.concat([Buffer.from(`${a}/`), b]);

type Flag = "skip-worktree" | "assume-unchanged" | "both-bits" | "none";
const flagArgs = (flag: Flag) =>
  flag === "both-bits"
    ? ["--skip-worktree", "--assume-unchanged"]
    : flag === "none"
      ? []
      : [`--${flag}`];
const setFlag = (dir: string, flag: Flag, paths: ReadonlyArray<string | Buffer>) => {
  if (flag === "none" || paths.length === 0) return;
  const stdin = Buffer.concat(paths.flatMap((p) => [Buffer.from(p), Buffer.from([0])]));
  git(dir, ["update-index", ...flagArgs(flag), "-z", "--stdin"], stdin);
};

const initRepo = (name: string) => {
  const dir = nfs.mkdtempSync(`${REPOS}/${name}-`);
  gits(dir, ["init", "-q", "-b", "main"]);
  gits(dir, ["config", "user.name", "Test"]);
  gits(dir, ["config", "user.email", "test@test.com"]);
  gits(dir, ["config", "core.trustctime", "false"]);
  return dir;
};
const write = (dir: string, rel: string | Buffer, content: string, mtime?: number) => {
  const abs = join(dir, rel);
  const parent = abs.toString("binary").replace(/\/[^/]*$/, "");
  nfs.mkdirSync(Buffer.from(parent, "binary"), { recursive: true });
  nfs.writeFileSync(abs, content);
  if (mtime !== undefined) nfs.utimesSync(abs, mtime, mtime);
};
// Same size and mtime as the indexed entry, so only a content hash can see the edit.
const editSame = (dir: string, rel: string | Buffer, content: string) => write(dir, rel, content, T);
const commitAll = (dir: string) => {
  gits(dir, ["add", "-A"]);
  gits(dir, ["commit", "-q", "-m", "fixture"]);
};

type Entry = { mode: string; oid: string; display: string };
const display = (b: Buffer) => JSON.stringify(b.toString("utf8"));

const walk = (root: string): Map<string, Entry> => {
  const out = new Map<string, Entry>();
  const files: Buffer[] = [];
  const visit = (rel: Buffer | null) => {
    const abs = rel === null ? Buffer.from(root) : (join(root, rel) as Buffer);
    for (const d of nfs.readdirSync(abs, { encoding: "buffer", withFileTypes: true })) {
      const name = d.name as unknown as Buffer;
      if (rel === null && name.toString() === ".git") continue;
      const childRel = rel === null ? name : Buffer.concat([rel, Buffer.from("/"), name]);
      const childAbs = join(root, childRel) as Buffer;
      if (d.isDirectory()) {
        if (nfs.existsSync(Buffer.concat([childAbs, Buffer.from("/.git")]))) {
          const oid = gits(childAbs.toString(), ["rev-parse", "HEAD"]).trim();
          out.set(childRel.toString("hex"), { mode: "160000", oid, display: display(childRel) });
        } else visit(childRel);
      } else if (d.isSymbolicLink()) {
        const oid = gits(root, ["hash-object", "--stdin"], nfs.readlinkSync(childAbs)).trim();
        out.set(childRel.toString("hex"), { mode: "120000", oid, display: display(childRel) });
      } else files.push(childRel);
    }
  };
  visit(null);
  const batch = files.filter((f) => !f.includes(10) && Buffer.from(f.toString("utf8")).equals(f));
  const oids = batch.length
    ? gits(root, ["hash-object", "--no-filters", "--stdin-paths"], batch.map((f) => f.toString()).join("\n") + "\n")
        .trim()
        .split("\n")
    : [];
  const oidOf = new Map(batch.map((f, i) => [f.toString("hex"), oids[i]!]));
  for (const f of files) {
    const abs = join(root, f);
    const oid =
      oidOf.get(f.toString("hex")) ??
      gits(root, ["hash-object", "--no-filters", "--stdin"], nfs.readFileSync(abs)).trim();
    const mode = nfs.statSync(abs).mode & 0o100 ? "100755" : "100644";
    out.set(f.toString("hex"), { mode, oid, display: display(f) });
  }
  return out;
};

const lsTree = (dir: string, ref: string) => {
  const out = new Map<string, Entry>();
  const raw = git(dir, ["ls-tree", "-r", "-z", "--full-tree", ref]);
  let start = 0;
  for (let i = 0; i < raw.length; i++) {
    if (raw[i] !== 0) continue;
    const rec = raw.subarray(start, i);
    start = i + 1;
    const tab = rec.indexOf(9);
    const [mode, , oid] = rec.subarray(0, tab).toString().split(" ");
    const p = Buffer.from(rec.subarray(tab + 1));
    out.set(p.toString("hex"), { mode: mode!, oid: oid!, display: display(p) });
  }
  return out;
};

const compareMaps = (expected: Map<string, Entry>, actual: Map<string, Entry>, label: string) => {
  const diffs: string[] = [];
  const extras: string[] = [];
  for (const [k, e] of expected) {
    const a = actual.get(k);
    if (!a) diffs.push(`${e.display} missing in ${label}`);
    else if (a.mode !== e.mode || a.oid !== e.oid)
      diffs.push(`${e.display}: ${label} ${a.mode} ${a.oid.slice(0, 10)} vs wt ${e.mode} ${e.oid.slice(0, 10)}`);
  }
  for (const k of actual.keys()) if (!expected.has(k)) extras.push(k);
  return { diffs, extras };
};

const compareTree = (dir: string, ref: string, wt: Map<string, Entry>, sparse: boolean) => {
  const tree = lsTree(dir, ref);
  const { diffs, extras } = compareMaps(wt, tree, "tree");
  let excluded = 0;
  let unexpected = extras;
  if (sparse && extras.length > 0) {
    const stdin = Buffer.concat(extras.flatMap((k) => [Buffer.from(k, "hex"), Buffer.from([0])]));
    const selRaw = git(dir, ["sparse-checkout", "check-rules", "-z"], stdin);
    const sel = new Set<string>();
    let s = 0;
    for (let i = 0; i < selRaw.length; i++)
      if (selRaw[i] === 0) {
        sel.add(selRaw.subarray(s, i).toString("hex"));
        s = i + 1;
      }
    unexpected = extras.filter((k) => sel.has(k));
    excluded = extras.length - unexpected.length;
  }
  for (const k of unexpected) diffs.push(`${tree.get(k)!.display} extra in tree (absent from wt)`);
  return { match: diffs.length === 0, diffCount: diffs.length, diffs: diffs.slice(0, 12), sparseExcluded: excluded };
};

const indexState = (dir: string) => {
  const g = `${dir}/.git`;
  const st: Record<string, string | number> = { index: sha(`${g}/index`) };
  if (nfs.existsSync(`${g}/index`)) st.indexMtimeMs = nfs.statSync(`${g}/index`).mtimeMs;
  for (const f of nfs.readdirSync(g)) if (f.startsWith("sharedindex.")) st[f] = sha(`${g}/${f}`);
  return st;
};
const tags = (dir: string) =>
  gits(dir, ["ls-files", "-v", "-z", "--sparse"]).split("\0").filter((l) => /^[a-zS]/.test(l)).slice(0, 8);

const summarize = (log: ReadonlyArray<ReadonlyArray<string>>) => {
  const freshReadTrees = log.filter(
    (a) => a.includes("read-tree") && (!a.includes("--reset") || a.includes("index.sparse=true")),
  ).length;
  const flaggedReAdds = log.filter((a) => a.includes("--index-info") && a.includes("-z")).length;
  return { freshReadTrees, flaggedReAdds, path: freshReadTrees > 0 ? "fresh-index fallback" : "reused index" };
};

const REF = CheckpointRef.make("refs/t3/checkpoints/ev23624");

const instrumentedDriver = Effect.fn("ev.driver")(function* (log: string[][]) {
  const live = yield* VcsProcess.VcsProcess;
  return yield* GitVcsDriver.makeVcsDriverShape().pipe(
    Effect.provideService(VcsProcess.VcsProcess, {
      run: (input) => {
        log.push([...input.args]);
        return live.run(input);
      },
    }),
  );
});

const errorText = (exit: Exit.Exit<unknown, unknown>) =>
  Exit.isFailure(exit) ? Cause.pretty(exit.cause).split("\n").slice(0, 2).join(" | ").slice(0, 400) : undefined;

const capture = Effect.fn("ev.capture")(function* (dir: string, sparse: boolean, readsFile?: string) {
  const log: string[][] = [];
  const driver = yield* instrumentedDriver(log);
  const indexBefore = indexState(dir);
  const tagsBefore = tags(dir);
  if (readsFile) nfs.writeFileSync(readsFile, "");
  const t0 = performance.now();
  const exit = yield* driver.checkpoints
    .captureCheckpoint({ cwd: dir, checkpointRef: REF })
    .pipe(Effect.timeout("60 seconds"), Effect.exit);
  const ms = Math.round(performance.now() - t0);
  const indexAfter = indexState(dir);
  const reads = readsFile ? nfs.readFileSync(readsFile, "utf8").split("\n").filter(Boolean) : undefined;
  const wt = walk(dir);
  const tree = Exit.isSuccess(exit) ? compareTree(dir, REF, wt, sparse) : null;
  const indexUnchanged = JSON.stringify(indexBefore) === JSON.stringify(indexAfter);
  return {
    ok: Exit.isSuccess(exit),
    error: errorText(exit),
    ms,
    tree,
    indexBefore,
    indexAfter,
    indexUnchanged,
    tagsBefore,
    ...summarize(log),
    ...(reads ? { rehashed: reads.length, rehashedPaths: reads.slice(0, 6) } : {}),
    wt,
  };
});

const record = (row: string, flag: string, result: Record<string, unknown>) => {
  const { wt: _wt, ...rest } = result;
  const line = JSON.stringify({ side: SIDE, row, flag, ...rest });
  console.log(`EV23624 ${line}`);
  nfs.appendFileSync(OUT, `${line}\n`);
};

const check = (r: { ok: boolean; tree: { match: boolean } | null; indexUnchanged: boolean }) => {
  assert.isTrue(r.ok, "capture succeeded");
  assert.isTrue(r.tree?.match, "checkpoint tree matches working tree");
  assert.isTrue(r.indexUnchanged, "real index unchanged");
};

const BOTH = ["skip-worktree", "assume-unchanged"] as const;

type Built = { dir: string; sparse: boolean; note?: string };
const rows: Array<{ id: string; flags: ReadonlyArray<Flag>; build: (flag: Flag) => Built }> = [];

const sparseBase = (name: string, mode: "cone-sparse-index" | "cone-full-index" | "non-cone", flag: Flag) => {
  const dir = initRepo(name);
  for (const f of ["in/a", "in/b", "out/x", "top"]) write(dir, f, "orig\n", T);
  commitAll(dir);
  if (mode === "cone-sparse-index") gits(dir, ["sparse-checkout", "set", "--cone", "--sparse-index", "in"]);
  if (mode === "cone-full-index") gits(dir, ["sparse-checkout", "set", "--cone", "--no-sparse-index", "in"]);
  if (mode === "non-cone") gits(dir, ["sparse-checkout", "set", "--no-cone", "/in/"]);
  gits(dir, ["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
  setFlag(dir, flag, ["in/a"]);
  editSame(dir, "in/a", "edit\n");
  return { dir, sparse: true };
};

rows.push({ id: "R1b", flags: BOTH, build: (flag) => sparseBase("r1b", "cone-sparse-index", flag) });

rows.push({
  id: "R2a",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r2a");
    write(dir, "f", "orig\n", T);
    write(dir, "g", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ["f"]);
    nfs.chmodSync(`${dir}/f`, 0o755);
    return { dir, sparse: false, note: "flagged f chmod +x" };
  },
});

rows.push({
  id: "R2b",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r2b");
    write(dir, "f", "orig\n", T);
    write(dir, "g", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ["g"]);
    nfs.chmodSync(`${dir}/f`, 0o755);
    return { dir, sparse: false, note: "unflagged f chmod +x, g flagged" };
  },
});

rows.push({
  id: "R4",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r4");
    write(dir, "old", "orig\n", T);
    write(dir, "keep", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ["old"]);
    nfs.renameSync(`${dir}/old`, `${dir}/new`);
    return { dir, sparse: false, note: "flagged old renamed to new" };
  },
});

rows.push({
  id: "R5",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r5");
    write(dir, "f", "head-1\n", T);
    write(dir, "keep", "orig\n", T);
    commitAll(dir);
    write(dir, "f", "stage1\n", T);
    gits(dir, ["add", "f"]);
    setFlag(dir, flag, ["f"]);
    editSame(dir, "f", "work-1\n");
    return { dir, sparse: false, note: "HEAD head-1, staged stage1, wt work-1 (same size+mtime)" };
  },
});

rows.push({
  id: "R9",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r9");
    write(dir, "a", "orig\n", T);
    write(dir, "b", "orig\n", T);
    commitAll(dir);
    gits(dir, ["update-index", "--split-index"]);
    write(dir, "c", "staged\n", T);
    gits(dir, ["add", "c"]);
    setFlag(dir, flag, ["a"]);
    editSame(dir, "a", "edit\n");
    return { dir, sparse: false, note: "split index + flagged same-size edit" };
  },
});

rows.push({ id: "R11", flags: BOTH, build: (flag) => sparseBase("r11", "cone-full-index", flag) });
rows.push({ id: "R12", flags: BOTH, build: (flag) => sparseBase("r12", "non-cone", flag) });

rows.push({
  id: "R13",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r13");
    write(dir, "top", "orig\n", T);
    const sub = `${dir}/sub`;
    nfs.mkdirSync(sub);
    gits(sub, ["init", "-q", "-b", "main"]);
    write(sub, "inner", "one\n");
    gits(sub, ["add", "."]);
    gits(sub, ["-c", "user.name=T", "-c", "user.email=t@t", "commit", "-q", "-m", "one"]);
    commitAll(dir);
    setFlag(dir, flag, ["sub"]);
    write(sub, "inner", "two\n");
    gits(sub, ["-c", "user.name=T", "-c", "user.email=t@t", "commit", "-q", "-am", "two"]);
    return { dir, sparse: false, note: "flagged gitlink, sub HEAD moved" };
  },
});

const ODD = ["new\nline", "tab\there", 'quo"te', "ünïcödé"];
rows.push({
  id: "R14",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r14");
    for (const p of [...ODD, "plain"]) write(dir, p, "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ODD);
    for (const p of ODD) editSame(dir, p, "edit\n");
    return { dir, sparse: false, note: "4 flagged odd paths, same-size edits" };
  },
});

const BAD = Buffer.from([0x62, 0xff, 0x61]);
rows.push({
  id: "R15",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r15");
    write(dir, BAD, "orig\n", T);
    write(dir, "plain", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, [BAD]);
    editSame(dir, BAD, "edit\n");
    return { dir, sparse: false, note: "flagged path b\\xffa, same-size edit" };
  },
});

rows.push({
  id: "R16",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r16");
    const names = Array.from({ length: 5000 }, (_, i) => `d/${"x".repeat(190)}${String(i).padStart(5, "0")}`);
    for (const n of names) write(dir, n, "orig\n", T);
    write(dir, "plain", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, names);
    editSame(dir, names[1234]!, "edit\n");
    return { dir, sparse: false, note: "5000 flagged ~200-char paths (>1 MiB of records)" };
  },
});

rows.push({ id: "R17-sparse", flags: ["both-bits"], build: (flag) => sparseBase("r17s", "cone-sparse-index", flag) });
rows.push({
  id: "R17-nonsparse",
  flags: ["both-bits"],
  build: (flag) => {
    const dir = initRepo("r17n");
    write(dir, "a", "orig\n", T);
    write(dir, "b", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ["a"]);
    editSame(dir, "a", "edit\n");
    return { dir, sparse: false, note: "'s' tag on non-sparse checkout" };
  },
});

rows.push({
  id: "R21",
  flags: BOTH,
  build: (flag) => {
    const dir = initRepo("r21");
    write(dir, "file.txt", "before\n", T);
    write(dir, "g", "orig\n", T);
    commitAll(dir);
    setFlag(dir, flag, ["g"]);
    nfs.utimesSync(`${dir}/.git/index`, T, T);
    write(dir, "file.txt", "after!\n", T);
    editSame(dir, "g", "edit\n");
    return { dir, sparse: false, note: "racy unflagged file.txt (index mtime == file mtime) + flagged g" };
  },
});

for (const row of rows) {
  for (const flag of row.flags) {
    it.effect(
      `${row.id} ${flag}`,
      () =>
        Effect.gen(function* () {
          const { dir, sparse, note } = row.build(flag);
          const r = yield* capture(dir, sparse);
          record(row.id, flag, { ...r, note, dir });
          check(r);
        }).pipe(Effect.provide(layerGitContract)),
      120_000,
    );
  }
}

// R19: restore a checkpoint captured through the reuse path into a scrambled working tree.
for (const variant of ["nonsparse", "cone-sparse"] as const) {
  for (const flag of BOTH) {
    it.effect(
      `R19 ${variant} ${flag}`,
      () =>
        Effect.gen(function* () {
          let dir: string;
          let flaggedPath: string;
          if (variant === "cone-sparse") {
            dir = sparseBase("r19s", "cone-sparse-index", flag).dir;
            flaggedPath = "in/a";
            write(dir, "in/b", "changed b\n");
            write(dir, "in/new", "untracked\n");
          } else {
            dir = initRepo("r19n");
            for (const f of ["a", "b", "c"]) write(dir, f, "orig\n", T);
            commitAll(dir);
            setFlag(dir, flag, ["a"]);
            editSame(dir, "a", "edit\n");
            write(dir, "b", "changed b\n");
            write(dir, "new", "untracked\n");
            flaggedPath = "a";
          }
          const r = yield* capture(dir, variant === "cone-sparse");
          const captured = r.wt;
          // Scramble: rewrite the flagged file, delete a tracked file, add a stray file.
          write(dir, flaggedPath, "scrambled!!\n");
          nfs.rmSync(`${dir}/${variant === "cone-sparse" ? "in/b" : "b"}`);
          write(dir, "stray", "stray\n");
          const log: string[][] = [];
          const driver = yield* instrumentedDriver(log);
          const restoreExit = yield* driver.checkpoints
            .restoreCheckpoint({ cwd: dir, checkpointRef: REF })
            .pipe(Effect.exit);
          const restored = walk(dir);
          const { diffs, extras } = compareMaps(captured, restored, "restored");
          for (const k of extras) diffs.push(`${restored.get(k)!.display} extra after restore`);
          const restore = {
            ok: Exit.isSuccess(restoreExit),
            error: errorText(restoreExit),
            match: diffs.length === 0,
            diffs,
            indexAfterRestore: indexState(dir),
            tagsAfterRestore: tags(dir),
          };
          record("R19", `${variant} ${flag}`, { ...r, restore, dir });
          check(r);
          assert.isTrue(restore.ok, "restore succeeded");
          assert.isTrue(restore.match, "restored working tree matches the captured one");
        }).pipe(Effect.provide(layerGitContract)),
      120_000,
    );
  }
}

// R20: 25,000-file timing with a counting clean filter.
for (const variant of ["old-mtime", "fresh-mtime"] as const) {
  for (const flag of ["none", "skip-worktree", "assume-unchanged"] as const) {
    it.effect(
      `R20 ${variant} ${flag}`,
      () =>
        Effect.gen(function* () {
          const dir = initRepo("r20");
          write(dir, ".gitattributes", "* filter=probe\n", variant === "old-mtime" ? T : undefined);
          for (let i = 0; i < 25_000; i++) {
            const name = `d${String(Math.floor(i / 1000)).padStart(2, "0")}/f${String(i).padStart(5, "0")}`;
            write(dir, name, `file ${String(i).padStart(5, "0")}\n`, variant === "old-mtime" ? T : undefined);
          }
          const t0 = performance.now();
          commitAll(dir);
          const setupCommitMs = Math.round(performance.now() - t0);
          gits(dir, ["config", "filter.probe.clean", "printf '%s\\n' %f >> .git/reads; cat"]);
          const target = "d00/f00007";
          setFlag(dir, flag, [target]);
          write(dir, target, "FILE 00007\n");
          const r = yield* capture(dir, false, `${dir}/.git/reads`);
          record("R20", `${variant} ${flag}`, {
            ...r,
            setupCommitMs,
            note: `25000 files, edited ${target}${flag === "none" ? "" : ` (${flag})`}`,
            dir,
          });
          check(r);
        }).pipe(Effect.provide(layerGitContract)),
      180_000,
    );
  }
}
