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

test("Bare-root containers are rejected with individual-worktree guidance", WEB, async ({ t3, app, screen, browser }) => {
  const source = await t3.project("Example repository", { "README.md": "Example repository\n" });
  const parent = mkdtempSync("/tmp/factory-pr-23407-a1794597635-evidence-2/demo-");
  const container = `${parent}/myproj`;
  mkdirSync(container);
  const git = (...args: string[]) => execFileSync("git", args, { cwd: container });
  git("clone", "--bare", source, ".bare");
  writeFileSync(`${container}/.git`, "gitdir: ./.bare\n");
  git("worktree", "add", "develop", "-b", "develop", "HEAD");
  git("config", "core.bare", "false");
  const primary = `${parent}/primary`;
  mkdirSync(primary);
  execFileSync("git", ["init", "--separate-git-dir", ".metadata", "."], { cwd: primary });
  execFileSync("git", ["worktree", "add", "--orphan", "-b", "feature", "../feature"], { cwd: primary });
  await t3.open();
  const addFolder = async (folder: string) => {
    await screen.getByRole("button", "Add project", { exact: true }).tap();
    await screen.getByText("Local folder", { exact: true }).tap();
    await screen.getByRole("combobox").fill(folder);
    await browser.keyboard.press("Enter");
  };
  await addFolder(`${container}/develop`);
  await screen.getByRole("button", "New thread in develop", { exact: true }).waitFor();
  await app.screenshot("individual-worktree-accepted");
  await addFolder(primary);
  await screen.getByRole("button", "New thread in primary", { exact: true }).waitFor();
  await app.screenshot("fresh-primary-accepted");
  await screen.getByRole("button", "Add project").tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  await screen.getByRole("combobox").fill(container);
  await browser.keyboard.press("Enter");
  await screen.getByText("Add one of its worktrees as the project instead.", { exact: false }).or(screen.getByRole("button", /^Changes Uncommitted/)).first().waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
    return true;
  });
  await app.screenshot("container-add-result");
  await expect(screen.getByText("Add one of its worktrees as the project instead.", { exact: false })).toBeVisible();
});
