import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A busy sibling project blocks switching a repository ending in a space", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = await t3.project("fixture");
  const root = `${fixture}/project `;
  await mkdir(`${root}/pkg`, { recursive: true });
  await mkdir(`${root}/other`, { recursive: true });
  await writeFile(`${root}/pkg/README.md`, "Package\n");
  await writeFile(`${root}/other/README.md`, "Other\n");
  await runPromise(run("git", ["init", "--quiet", "--initial-branch=main"], { cwd: root }));
  await runPromise(run("git", ["add", "."], { cwd: root }));
  await runPromise(run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial"], { cwd: root }));
  await runPromise(run("git", ["branch", "feature"], { cwd: root }));
  const { cli } = makeState(T3_HOME);
  await runPromise(cli(["project", "add", `${root}/pkg`, "--title", "pkg"]));
  await runPromise(cli(["project", "add", `${root}/other`, "--title", "other"]));
  await t3.thread({ project: `${root}/pkg`, title: "Busy pkg turn", messages: ["Ask a question"], model: "question" });
  const idle = await t3.thread({ project: `${root}/other`, title: "Idle other thread", messages: ["Showcase"], model: "showcase" });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(idle);
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click();
  await screen.getByRole("option", /^feature\b/).tap();
  // Both outcomes settle through the branch action: either its failure toast or the new branch label.
  await browser.locator('[data-slot="combobox-trigger"][aria-label="Branch: feature"]:visible, [data-slot="toast-description"]').first().waitFor();
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible:enabled').waitFor();
  await app.screenshot("branch-switch-with-busy-sibling");
  const branch = await runPromise(run("git", ["branch", "--show-current"], { cwd: root }));
  expect(branch.stdout.trim(), "The busy sibling must keep the shared checkout on main").toBe("main");
});
