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

test("A sole github remote identifies trunk and confirms the default-branch action", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("default-branch-demo", { "README.md": "# Demo\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, stdio: "pipe" });
  git("branch", "-m", "trunk");
  git("init", "--bare", "--initial-branch=trunk", `${project}.git`);
  git("remote", "add", "github", `${project}.git`);
  git("push", "--set-upstream", "github", "trunk");
  git("remote", "set-head", "github", "trunk");
  writeFileSync(`${project}/README.md`, "# Demo\n\nA local edit ready to commit.\n");
  await t3.thread({ project, title: "Review local changes", messages: ["Ready"] });
  await t3.open();
  await screen.getByRole("button", "Review local changes, Done, default-branch-demo").tap();
  const action = screen.getByRole("button", /^Commit(?: & push|, push & PR)$/);
  await action.waitFor({ state: "visible" });
  await screen.getByText("Syncing messages...").waitFor({ state: "hidden" });
  await app.screenshot("primary-git-action");
  await action.tap();
  await screen.getByRole("dialog", /^(Action failed|Commit & push to default ref\?)$/).waitFor({ state: "visible" });
  await app.screenshot("default-branch-confirmation");
  await expect(screen.getByRole("heading", "Commit & push to default ref?")).toBeVisible();
  await screen.getByRole("button", "Abort").tap();
  await screen.getByRole("dialog", "Commit & push to default ref?").waitFor({ state: "detached" });
  await expect(screen.getByRole("button", "Commit & push", { exact: true })).toBeVisible();
  await app.screenshot("cancelled-confirmation");
});
