import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("A checkpoint preserves a separate Git directory ending in a space", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("checkpoint-space", { "hello.txt": "hello\n" });
  await runPromise(run("git", ["init", `--separate-git-dir=${Path.join(Path.dirname(project), "metadata ")}`], { cwd: project }));
  const thread = await t3.thread({ project, title: "Checkpoint with trailing-space Git metadata", model: "question", messages: ["Append edited by agent to hello.txt"] });
  await t3.open(thread);
  await screen.getByText("Strict schemas (Recommended)", { exact: true }).waitFor();
  // Replay supplies the provider lifecycle; stage its deterministic file edit while the question holds the turn open.
  await FS.appendFile(Path.join(project, "hello.txt"), "edited by agent\n");
  await screen.getByText("Strict schemas (Recommended)", { exact: true }).tap();
  await screen.getByText("plan questions fixture complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await app.screenshot("checkpoint-result");
  const refs = await runPromise(run("git", ["for-each-ref", "--format=%(refname)", "refs/t3"], { cwd: project }));
  const namesForReport = refs.stdout.trim().split("\n").filter(Boolean);
  const baselineForReport = namesForReport.find((name) => name.endsWith("/ordinal/0"));
  const finalForReport = namesForReport.find((name) => name.endsWith("/ordinal/1"));
  const capturedDiff = baselineForReport && finalForReport
    ? (await runPromise(run("git", ["diff", baselineForReport, finalForReport, "--", "hello.txt"], { cwd: project }))).stdout
    : "No checkpoint diff available: baseline and final refs missing.";
  await FS.writeFile(`/tmp/factory-pr-41725-evidence-1/checkpoint-${Date.now()}.txt`,
    `Separate Git directory basename: "metadata " (one trailing space)\nhello.txt: ${JSON.stringify(await FS.readFile(Path.join(project, "hello.txt"), "utf8"))}\nCheckpoint refs:\n${refs.stdout || "(none)\n"}\nCheckpoint diff:\n${capturedDiff}`);
  expect(refs.stdout).toContain("/ordinal/0");
  expect(refs.stdout).toContain("/ordinal/1");
  const names = refs.stdout.trim().split("\n");
  const before = names.find((name) => name.endsWith("/ordinal/0"))!;
  const after = names.find((name) => name.endsWith("/ordinal/1"))!;
  const diff = await runPromise(run("git", ["diff", before, after, "--", "hello.txt"], { cwd: project }));
  expect(diff.stdout).toContain("+edited by agent");
});
