import { execFileSync } from "node:child_process";
import { writeFileSync, readFileSync, existsSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A branch checkout exceeding ten seconds finishes cleanly", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Slow checkout", { "old-branch.txt": "original branch\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  git("checkout", "-b", "slow-target");
  git("rm", "old-branch.txt");
  writeFileSync(`${project}/.gitattributes`, "slow.txt filter=slow\n");
  writeFileSync(`${project}/slow.txt`, "selected branch contents\n");
  git("add", ".");
  git("commit", "-m", "Target branch");
  git("checkout", "main");
  git("config", "filter.slow.smudge", "sleep 15; cat");
  git("config", "filter.slow.clean", "cat");
  git("config", "filter.slow.required", "true");
  await t3.open();
  await screen.getByText("main", { exact: true }).first().tap();
  await screen.getByRole("option", "slow-target", { exact: false }).tap();
  // Give the same real Git filter time to finish on either app revision.
  await new Promise(resolve => setTimeout(resolve, 11000));
  await app.screenshot("checkout-at-eleven-seconds");
  await new Promise(resolve => setTimeout(resolve, 8000));
  await app.screenshot("checkout-finished");
  const state = {
    branch: git("branch", "--show-current"),
    status: git("status", "--porcelain"),
    indexMatchesTarget: git("diff", "--cached", "slow-target", "--name-only") === "",
    contents: existsSync(`${project}/slow.txt`) ? readFileSync(`${project}/slow.txt`, "utf8") : "<missing>",
  };
  console.log("Checkout result:", JSON.stringify(state));
  expect(state).toEqual({ branch: "slow-target", status: "", indexMatchesTarget: true, contents: "selected branch contents\n" });
});
