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

test("Worktree fetch identifies a broken local ref", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Ref diagnostics");
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
  git(project, "branch", "-m", "dev");
  const remote = `${project}-remote.git`;
  const writer = `${project}-writer`;
  git(project, "clone", "--bare", project, remote);
  git(project, "remote", "add", "origin", remote);
  git(project, "fetch", "origin");
  git(project, "branch", "--set-upstream-to=origin/dev", "dev");
  const thread = await t3.thread({ project, title: "Inspect local refs", messages: ["first"] });
  git(project, "clone", remote, writer);
  writeFileSync(`${writer}/remote-update.txt`, "A newer remote commit\n");
  git(writer, "add", ".");
  git(writer, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Remote update");
  git(writer, "push", "origin", "dev");
  git(project, "fetch", "--dry-run", "--no-tags", "--", "origin", "+refs/heads/dev:refs/remotes/origin/dev");
  mkdirSync(`${project}/.git/refs/remotes/origin`, { recursive: true });
  writeFileSync(`${project}/.git/refs/remotes/origin/dev 2`, `${git(project, "rev-parse", "refs/remotes/origin/dev")}\n`);
  await t3.open(thread);
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  await screen.getByRole("combobox", "Workspace").tap();
  await screen.getByRole("option", "New worktree").tap();
  await screen.getByRole("combobox", /^Branch: From dev/).first().tap();
  await screen.getByRole("switch", "Start worktree from remote").check();
  await browser.keyboard.press("Escape");
  // Mask only the synthetic repository path in captures; leave the diagnostic and assertions intact.
  await browser.evaluate((privatePath) => {
    const masks = document.createElement("div");
    masks.dataset.evidenceMasks = "true";
    masks.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483647";
    document.body.append(masks);
    const paint = () => {
      const rects: DOMRect[] = [];
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (masks.contains(node)) continue;
        const start = node.textContent?.indexOf(privatePath) ?? -1;
        if (start < 0) continue;
        const range = document.createRange();
        range.setStart(node, start);
        range.setEnd(node, start + privatePath.length);
        rects.push(...range.getClientRects());
      }
      masks.replaceChildren(...rects.map((rect) => {
        const mask = document.createElement("div");
        mask.style.cssText = `position:fixed;left:${rect.x}px;top:${rect.y}px;width:${rect.width}px;height:${rect.height}px;background:#ddd;border-radius:2px`;
        return mask;
      }));
    };
    const observer = new MutationObserver((changes) => {
      if (changes.some((change) => !masks.contains(change.target))) paint();
    });
    observer.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
    window.addEventListener("resize", paint);
    document.addEventListener("scroll", paint, true);
    paint();
  }, project);
  await screen.getByRole("textbox").fill("Check this worktree");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByRole("alert").waitFor({ state: "visible" });
  await screen.getByRole("button", "Show full error").tap();
  const shot = await app.screenshot("fetch-diagnostic");
  const bounds = await browser.evaluate(() => {
    const rect = document.querySelector('[role="alert"]')!.getBoundingClientRect();
    return { x: Math.floor(rect.x), y: Math.floor(rect.y), width: Math.ceil(rect.width), height: Math.ceil(rect.height) };
  });
  execFileSync("convert", [shot, "-crop", `${bounds.width}x${bounds.height}+${bounds.x}+${bounds.y}`, "+repage", shot]);
  await expect(screen.getByText("Git found a broken local ref. Check the local repository on the server for a damaged or stray ref, then retry.", { exact: false }).first()).toBeVisible();
});
