import { readFile } from "node:fs/promises";
import { PNG } from "pngjs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Watch preflight rejects missing glab despite cached successful summaries", WEB, async ({ t3, app, screen, browser }) => {
  const stableCapture = async (label: string) => {
    await browser.evaluate(async () => { await document.fonts.ready; (document.activeElement as HTMLElement)?.blur(); });
    let previous: Buffer | undefined;
    for (let attempt=0; attempt<20; attempt++) {
      const file = await app.screenshot(`${label}-${attempt}`);
      const pixels = PNG.sync.read(await readFile(file)).data;
      if (previous?.equals(pixels)) return;
      previous = pixels;
      await new Promise((resolve) => setTimeout(resolve, 500));
    }
    throw new Error(`The ${label} capture did not become pixel-stable`);
  };
  const project = await t3.project("Watch proof", {
    ".git/config": '[core]\nrepositoryformatversion = 0\nbare = false\n[remote "origin"]\nurl = https://gitlab.example.test/proof/demo.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n',
  });
  await t3.thread({project, title:"Hosting dependency proof", model:"multi-turn", messages:["Warm successful summaries for MR 1 and MR 2"]});
  await t3.open();
  await screen.getByTestId("sidebar-row-card").first().tap();
  await screen.getByText("Ready to remove glab.", {exact:false}).waitFor({state:"visible"});
  await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden"});
  await stableCapture("successful-summaries-cached");
  await screen.getByRole("textbox").fill("Remove glab, watch linked MR 1 and unlinked MR 2 by their full URLs, then list the persisted links.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("Proof run complete.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await stableCapture("watch-results");
  await expect(screen.getByText("MR 1 watch: inactive", {exact:false})).toBeVisible();
  await expect(screen.getByText("MR 2 link: absent", {exact:false})).toBeVisible();
  await expect(screen.getByText("is required to browse change requests on this host.", {exact:false}).first()).toBeVisible();
});
