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

test("Literal POSIX backslashes keep their own repository-path group", WEB, async ({ t3, app, screen, browser }) => {
  const setup = await t3.project("Scenario setup");
  const thread = await t3.thread({ project: setup, title: "Path grouping", messages: ["Start"] });
  const repo = mkdtempSync("/tmp/factory-pr-44843-evidence-1/demo-repo-");
  for (const suffix of ["a\\b", "a/b"]) {
    mkdirSync(`${repo}/${suffix}`, { recursive: true });
    writeFileSync(`${repo}/${suffix}/README.md`, suffix);
  }
  const git = (args: string[]) => execFileSync("git", args, { cwd: repo });
  git(["init", "--quiet"]);
  git(["remote", "add", "origin", "https://github.com/example-org/demo-repo.git"]);
  git(["add", "."]);
  git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Two distinct folders"]);
  const { cli } = makeState(T3_HOME);
  const literal = `${repo}/a\\b`;
  const nested = `${repo}/a/b`;
  for (const path of [literal, nested]) await runPromise(cli(["project", "add", path, "--title", "example-org/demo-repo"]));
  await browser.setViewport({ width: 1600, height: 1100 });
  await t3.open(thread);
  const group = "github.com/example-org/demo-repo";
  await t3.open(`/settings/projects?project=${encodeURIComponent(group)}`);
  await screen.getByRole("combobox", new RegExp("Grouping rule for .*a\\\\b on")).tap();
  await screen.getByRole("option", "Group by repository path", { exact: true }).tap();
  await t3.open(`/settings/projects?project=${encodeURIComponent(group)}`);
  await screen.getByRole("combobox", new RegExp("Grouping rule for .*a/b on")).tap();
  await screen.getByRole("option", "Group by repository path", { exact: true }).tap();
  await screen.getByRole("button", /^Project scope:/).tap();
  await app.screenshot("repository-path-groups");
  await expect(screen.getByRole("menuitemradio", /example-org\/demo-repo/)).toHaveCount(2);
});
