/// <reference lib="dom" />
import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Git 2.34.1 refuses a worktree container as a project", WEB, async ({ t3, app, browser, screen }) => {
  const oldGit = "/tmp/factory-pr-43224-evidence-1/old-git/bin/git";
  // The runner already puts this directory first on the server's PATH.
  await symlink(oldGit, `${T3_HOME}/bin/git`);
  const fixture = await mkdtemp("/tmp/factory-pr-43224-evidence-1/fixture-");
  const source = `${fixture}/source`;
  const container = `${fixture}/container`;
  await mkdir(source);
  await mkdir(container);
  const git = (cwd: string, ...args: string[]) => runPromise(run(oldGit, args, { cwd }));
  await git(source, "init", "-b", "master");
  await writeFile(`${source}/README.md`, "Synthetic worktree example\n");
  await git(source, "add", ".");
  await git(source, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Initial commit");
  await git(container, "clone", "--bare", source, ".bare");
  await writeFile(`${container}/.git`, "gitdir: ./.bare\n");
  await git(container, "worktree", "add", "master", "master");
  await runPromise(run(oldGit, ["worktree", "list", "--porcelain", "-z"], { cwd: container, allowExit: [129] }));
  await runPromise(makeState(T3_HOME).cli(["project", "add", `${container}/master`]));
  const demo = await t3.project("demo");
  const thread = await t3.thread({ project: demo, title: "Worktree container validation", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("combobox", "Projects").tap();
  await screen.getByRole("option", "Add project").tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  await screen.getByRole("combobox").fill(container);
  await browser.keyboard.press("Enter");
  // Both outcomes finish in the UI: rejection toast, or successful navigation to the project.
  await browser.evaluate(async () => {
    const done = () => document.body.innerText.includes("Failed to add project") || !document.querySelector('[role="dialog"]');
    if (done()) return;
    await new Promise<void>((resolve) => {
      const observer = new MutationObserver(() => {
        if (done()) { observer.disconnect(); resolve(); }
      });
      observer.observe(document.body, { childList: true, subtree: true, attributes: true });
    });
  });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
  });
  await app.screenshot("adding-container-with-git-2.34.1");
  await expect(screen.getByText(/holds a repository's worktrees but is not a checkout itself/)).toBeVisible();
});
