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

test("Ignore wildcards treat regular files and symlinks as UTF-8 bytes", WEB, async ({ t3, app, screen, browser }) => {
  const cases = [
    { title: "One-byte wildcard", ignore: "?.txt\nreg-?.txt\n", label: "one-byte-wildcard" },
    { title: "Two-byte wildcard", ignore: "??.txt\nreg-??.txt\n", label: "two-byte-wildcard" },
    { title: "Literal Unicode", ignore: "ø.txt\nreg-é.txt\n", label: "literal-unicode" },
  ];
  const fixtures = [];
  for (const item of cases) {
    const project = await t3.project(item.title, {
      ".ignore": item.ignore,
      "target": "synthetic symlink target\n",
      "b.txt": "ascii\n", "reg-a.txt": "ascii\n", "reg-ab.txt": "ascii\n",
      "reg-é.txt": "two bytes\n", "reg-中.txt": "three bytes\n", "reg-🎉.txt": "four bytes\n",
    });
    for (const name of ["ø.txt", "界.txt", "😀.txt"]) symlinkSync("target", `${project}/${name}`);
    execFileSync("git", ["add", "--all"], { cwd: project });
    execFileSync("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Add synthetic symlinks"], { cwd: project });
    const thread = await t3.thread({ project, title: item.title, messages: ["first"] });
    fixtures.push({ ...item, thread });
  }
  const results: string[][] = [];
  for (const item of fixtures) {
    await t3.open(item.thread);
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ state: "visible" });
    await browser.keyboard.press("ControlOrMeta+p");
    await screen.getByPlaceholder("Search files…").fill(".txt");
    await expect(screen.getByText("reg-🎉.txt", { exact: true }).first()).toBeVisible();
    await app.screenshot(item.label);
    results.push(await browser.evaluate(() => Array.from(document.querySelectorAll('[role="option"]')).map(el => el.textContent ?? "")));
    await browser.keyboard.press("Escape");
  }
  const includes = (index: number, name: string) => results[index]!.some(text => text.includes(name));
  for (const name of ["ø.txt", "界.txt", "😀.txt"]) expect(includes(0, name)).toBe(true);
  expect(includes(1, "ø.txt")).toBe(false);
  for (const name of ["界.txt", "😀.txt"]) expect(includes(1, name)).toBe(true);
  expect(includes(2, "ø.txt")).toBe(false);
  expect(includes(2, "reg-é.txt")).toBe(false);
  for (const name of ["界.txt", "😀.txt"]) expect(includes(2, name)).toBe(true);
});
