import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Git 2.34.1 attributes a committed turn without importing older upstream files", WEB, async ({ t3, app, screen }) => {
  const oldGit = process.env.GIT234_ROOT;
  if (!oldGit) throw new Error("Set GIT234_ROOT to the extracted Ubuntu 22.04 usr directory");
  writeFileSync(join(T3_HOME, "bin/git"), `#!/bin/sh\nexport GIT_EXEC_PATH=${oldGit}/lib/git-core\nexec ${oldGit}/bin/git "$@"\n`, { mode: 0o755 });
  const project = await t3.project("Git 2.34.1 checkpoint", { "README.md": "Checkpoint compatibility demonstration\n" });
  const git = (...args: string[]) => execFileSync(join(T3_HOME, "bin/git"), args, { cwd: project, encoding: "utf8" });
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  // Prepare an old upstream commit outside the turn, then bring it in during the turn.
  git("checkout", "-b", "upstream");
  writeFileSync(join(project, "upstream-only.txt"), "An older upstream change; not authored by this turn.\n");
  git("add", ".");
  git("commit", "-m", "Older upstream change", "--date=2020-01-01T00:00:00Z");
  // Authorship uses committer date as well as author date.
  execFileSync(join(T3_HOME, "bin/git"), ["commit", "--amend", "--no-edit"], { cwd: project, env: { ...process.env, GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z" } });
  git("checkout", "main");
  const thread = await t3.thread({ project, title: "Git 2.34.1 — committed turn attribution", model: "showcase", messages: ["Prepare the checkpoint demonstration."] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Commit turn-authored.txt while incorporating the older upstream commit.");
  await screen.getByRole("textbox").press("Enter");
  const stop = screen.getByRole("button", "Stop generation");
  await expect(stop).toBeVisible();
  git("merge", "--ff-only", "upstream");
  writeFileSync(join(project, "turn-authored.txt"), "This file was authored and committed during the turn.\n");
  git("add", ".");
  git("commit", "-m", "Commit the turn authored file");
  await expect(stop).toBeHidden({ timeout: 60000 });
  await app.screenshot("checkpoint-authorship");
  await expect(screen.getByText("turn-authored.txt", { exact: true }).first()).toBeVisible();
  await expect(screen.getByText("upstream-only.txt", { exact: true })).toBeHidden();
});
