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

test("Settings preserves the literal backslash in POSIX checkout labels", WEB, async ({ t3, app, screen, browser }) => {
  const root = `/tmp/factory-pr-44607-evidence-1/repos-${Date.now()}`;
  const paths = ["build\\log.txt", "control"].map((name) => `${root}/${name}`);
  for (const path of paths) {
    mkdirSync(path, { recursive: true });
    writeFileSync(`${path}/README.md`, "Synthetic scope demo\n");
    const git = (...args: string[]) => execFileSync("git", args, { cwd: path });
    git("init", "--quiet", "--initial-branch=main");
    git("add", ".");
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit");
    git("remote", "add", "origin", "https://github.com/example-org/scope-demo.git");
    await runPromise(makeState(T3_HOME).cli(["project", "add", path]));
  }
  const thread = await t3.thread({ project: paths[0]!, title: "Checkout scope demo", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/labs");
  await screen.getByRole("button", "Project scope: All projects").tap();
  await screen.getByRole("menuitemradio").filter({ hasText: "scope-demo" }).tap();
  await screen.getByRole("button", "Checkout scope: All checkouts").tap();
  const checkout = screen.getByRole("menuitemradio").filter({ hasText: paths[0]! });
  await checkout.waitFor();
  await app.screenshot("checkout-menu");
  // Select by its full path, which is correct even when its primary label is broken.
  await checkout.tap();
  await browser.locator('button[aria-label^="Checkout scope:"]').waitFor();
  await app.screenshot("selected-checkout");
  await expect(screen.getByRole("button", "Checkout scope: build\\log.txt")).toBeVisible();
  await browser.locator('button[aria-label^="Checkout scope:"]').click();
  await expect(screen.getByRole("menuitemradio").filter({ hasText: paths[0]! })).toContainText("build\\log.txt");
});
