/// <reference lib="dom" />
import { expect } from "e2e";
import { writeFile, chmod } from "node:fs/promises";
import { APP_DIR } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Commit descriptions and hook output keep regional-indicator flags whole", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("flag-boundaries", { "README.md": "Initial content\n" });
  const thread = await t3.thread({ project, title: "Flag truncation", messages: ["Start"], model: "default" });
  for (const [key, value] of [["user.name", "Scenario"], ["user.email", "scenario@example.invalid"], ["core.hooksPath", ".git/hooks"]]) {
    await runPromise(run("git", ["config", key!, value!], { cwd: project }));
  }
  await browser.setViewport({ width: 1920, height: 1080 });
  await t3.open(thread);
  const observed: string[] = [];
  let change = 0;
  const commit = async (prefix: number) => {
    await writeFile(`${project}/README.md`, `Change ${++change}\n`);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByRole("button", "Open README.md in editor", { exact: true }).waitFor();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill("a".repeat(prefix) + "🇯🇵bbbb");
    await screen.getByRole("button", "Commit", { exact: true }).tap();
  };
  const captureSuccess = async (label: string) => {
    await screen.getByText(/^Committed [0-9a-f]{7}$/).waitFor();
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
    const text = await browser.evaluate(() => [...document.querySelectorAll('[role="status"]')].find(e => /Committed [0-9a-f]{7}/.test(e.textContent ?? ""))?.querySelectorAll("p")[1]?.textContent ?? "MISSING");
    await app.screenshot(`${label}-normal`);
    await browser.evaluate(() => {
      const p = [...document.querySelectorAll('[role="status"]')].find(e => /Committed [0-9a-f]{7}/.test(e.textContent ?? ""))?.querySelectorAll("p")[1];
      if (p) { p.style.textOverflow = "clip"; p.scrollLeft = p.scrollWidth; }
    });
    await app.screenshot(label);
    await browser.mouse.move(1000, 500);
    return text;
  };
  await commit(67);
  observed.push(await captureSuccess("commit-cut-through-flag"));
  await writeFile(`${project}/.git/hooks/pre-commit`, "#!/bin/sh\nprintf '%s\\n' '" + "a".repeat(498) + "🇯🇵bbbb'\nsleep 6\n");
  await chmod(`${project}/.git/hooks/pre-commit`, 0o755);
  await commit(67);
  await screen.getByText("Running pre-commit...", { exact: true }).waitFor();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
  const output = await browser.evaluate(() => [...document.querySelectorAll('[role="status"]')].find(e => e.textContent?.includes("Running pre-commit"))?.querySelectorAll("p")[2]?.textContent ?? "MISSING");
  await app.screenshot("hook-cut-through-flag-normal");
  await browser.evaluate(() => {
    const p = [...document.querySelectorAll('[role="status"]')].find(e => e.textContent?.includes("Running pre-commit"))?.querySelectorAll("p")[2];
    if (p) { p.style.textOverflow = "clip"; p.scrollLeft = p.scrollWidth; }
  });
  await app.screenshot("hook-cut-through-flag");
  await browser.mouse.move(1000, 500);
  observed.push(output);
  observed.push(await captureSuccess("commit-after-hook"));
  await writeFile(`${project}/.git/hooks/pre-commit`, "#!/bin/sh\nexit 0\n");
  await commit(65);
  observed.push(await captureSuccess("whole-flag-fits"));
  const sha = (await runPromise(run("git", ["rev-parse", "HEAD"], { cwd: APP_DIR }))).stdout.trim();
  await writeFile(`${process.env.T3_FLAG_EVIDENCE_DIR}/observed-${sha}.json`, JSON.stringify({ sha, observed: observed.map(text => ({ text, utf16Length: text.length, tailCodePoints: Array.from(text).slice(-8).map(c => c.codePointAt(0)!.toString(16)) })) }, null, 2));
  expect(observed).toEqual(["a".repeat(67) + "...", "a".repeat(498), "a".repeat(67) + "...", "a".repeat(65) + "🇯🇵..."]);
});
