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

test("PR checkout retains its originating pull request after first send and reload", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("PR checkout demo");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
  git("remote", "add", "origin", "https://github.com/pingdotgg/t3code.git");
  git("fetch", "--quiet", APP_DIR, "f9afb67325728d8e5dadc2278b44b6fd1aa53b14");
  git("update-ref", "refs/remotes/origin/fix/link-pr-on-checkout", "f9afb67325728d8e5dadc2278b44b6fd1aa53b14");
  const results: boolean[] = [];
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(`${label}-stability`);
    for (let i = 0; i < 10; i++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(label);
      if (readFileSync(previous).equals(readFileSync(current))) return;
      previous = current;
    }
    throw new Error("The capture did not settle");
  };
  const sendAndInspect = async (label: string, message?: string) => {
    await screen.getByRole("combobox").filter({hasText:"t3code/pr-15848"}).first().waitFor({state:"visible"});
    if (message) await screen.getByTestId("composer-editor").fill(message);
    await screen.getByRole("button", "Submit message", {exact:true}).tap();
    await screen.getByText("This turn is a replay.", { exact: false }).waitFor({state:"visible", timeout:120000});
    await screen.getByRole("button", "Stop generation", {exact:true}).waitFor({state:"hidden"});
    await browser.reload();
    await screen.getByTestId("composer-editor").waitFor({state:"visible"});
    if (!(await screen.getByRole("region", "Workspace panel", {exact:true}).count())) {
      await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
    }
    await screen.getByRole("button", "Add panel surface", {exact:true}).tap();
    const linkedRequests = screen.getByRole("menuitem", "Linked pull requests", {exact:false});
    await linkedRequests.waitFor({state:"visible"});
    const linked = await linkedRequests.isEnabled();
    if (linked) await linkedRequests.tap();
    else await browser.keyboard.press("Escape");
    await stableCapture(label);
    results.push(linked && await screen.getByRole("link").filter({hasText:"#15848"}).last().isVisible());
  };
  await t3.open();
  await screen.getByRole("combobox").filter({hasText: "main"}).first().tap();
  await screen.getByPlaceholder("Search refs...").fill("15848");
  await screen.getByText("Checkout pull request", { exact: false }).tap();
  await screen.getByRole("button", "Worktree", { exact: true }).tap();
  await screen.getByRole("dialog", "Checkout pull request", {exact:true}).waitFor({state:"hidden", timeout:120000});
  await sendAndInspect("chat-checkout-after-reload", "Explain this change briefly");

  await t3.open("/pull-requests?repository=pingdotgg%2Ft3code&number=15848&involvement=all&state=all");
  await screen.getByRole("button", "Check out", {exact:true}).tap();
  await screen.getByRole("menuitem", "In a separate worktree", {exact:false}).tap();
  await browser.waitForURL(/\/draft\//, {timeout:120000});
  await sendAndInspect("detail-checkout-after-reload", "Explain the PR detail checkout");

  await t3.open("/pull-requests?repository=pingdotgg%2Ft3code&number=15848&involvement=all&state=all");
  await screen.getByRole("button", "More pull request actions", {exact:true}).tap();
  await screen.getByRole("menuitem", "Fix findings in a thread", {exact:false}).tap();
  await browser.waitForURL(/\/draft\//, {timeout:120000});
  await sendAndInspect("finding-handoff-after-reload");
  expect(results).toEqual([true, true, true]);
});
