import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { setTimeout as delay } from "node:timers/promises";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("SHA-256 PR commit links retain their commit scope", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("sha256demo", {
    ".git/config": '[core]\nrepositoryformatversion = 1\n[extensions]\nobjectformat = sha256\n[remote "origin"]\nurl = http://127.0.0.1:3917/tester/sha256demo.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n',
  });
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  await git("fetch", "origin");
  await git("checkout", "-B", "feature", "origin/feature");
  const url = "http://127.0.0.1:3917/tester/sha256demo/pulls/1/commits/3a45bc33121f643ad15c9d50329e0db59a5b7d9409398ceda68f5bb69b676cdf";
  const thread = await t3.thread({project, title: "SHA-256 commit links", messages: [url + "\n\n" + url + "#diff-83348d283c1ba0b3b4d55fdc04c39a165b933125R5"]});
  const stableCapture = async (label: string) => {
    await browser.mouse.move(870, 930);
    await delay(1000);
    let previous = await app.screenshot(`${label}-settling`);
    for (let i = 0; i < 6; i++) {
      await delay(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("Capture did not settle");
  };
  await browser.setViewport({width: 1440, height: 960});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent http/).tap();
  await browser.locator(`a[href="${url}"]`).first().click();
  await screen.getByRole("heading", "Add line five", {exact: true}).waitFor();
  if (await screen.getByRole("button", /^Diff scope:/).isVisible()) {
    await screen.getByText("notes.txt", {exact: true}).first().waitFor();
    await screen.getByRole("status", "Loading pull request diff...").waitFor({state:"hidden"});
  }
  await stableCapture("bare-commit-link");
  const bareSelected = await screen.getByRole("button", "Diff scope: Add line five", {exact:true}).isVisible();
  await browser.locator(`a[href="${url}#diff-83348d283c1ba0b3b4d55fdc04c39a165b933125R5"]`).first().click();
  await screen.getByRole("button", /^Diff scope:/).waitFor();
  await screen.getByText("notes.txt", {exact: true}).first().waitFor();
  await screen.getByRole("status", "Loading pull request diff...").waitFor({state:"hidden"});
  await browser.locator("[data-line][data-selected-line]").first().waitFor();
  await stableCapture("diff-line-commit-link");
  const lineSelected = await screen.getByRole("button", "Diff scope: Add line five", {exact:true}).isVisible();
  expect({bareSelected, lineSelected}, "Both links open the named commit's Code patch").toEqual({bareSelected:true, lineSelected:true});
});
