import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { setTimeout as pause } from "node:timers/promises";
import { test, WEB } from "./t3.ts";

// Read-only GitHub fixture: this completed PR targets main. The local branch is retained.
// No repository or PR is created or modified on GitHub.
test("New threads do not inherit a completed branch PR", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Integration branch", {
    "README.md": "Synthetic workspace for reusing an integration branch.\n",
  });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
  git("remote", "add", "origin", "https://github.com/pingdotgg/t3code.git");
  git("update-ref", "refs/remotes/origin/main", "HEAD");
  git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
  git("checkout", "-b", "fix/issue-33743");
  git("update-ref", "refs/remotes/origin/fix/issue-33743", "HEAD");
  git("config", "branch.fix/issue-33743.remote", "origin");
  git("config", "branch.fix/issue-33743.merge", "refs/heads/fix/issue-33743");

  const refreshStatus = async () => {
    await browser.evaluate(async (cwd: string) => {
      const { vcsEnvironment } = await import("/src/state/vcs.ts");
      const { appAtomRegistry } = await import("/src/rpc/atomRegistry.ts");
      const { readPrimaryEnvironmentId } = await import("/src/state/environments.ts");
      const result = await vcsEnvironment.refreshStatus.run(appAtomRegistry, {
        environmentId: readPrimaryEnvironmentId(), input: { cwd, localOnly: false },
      });
      if (result._tag === "Failure") throw new Error("Git status refresh failed");
      if (result.value.pr?.number !== 33745) throw new Error("Historical PR fixture was not returned by Git status");
      return true;
    }, project);
  };
  const selectRetainedBranch = async () => {
    await screen.getByRole("combobox").filter({ hasText: "fix/issue-33743" }).first().tap();
    await screen.getByRole("option", { name: "fix/issue-33743", exact: false }).first().tap();
  };
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 20; attempt++) {
      await pause(500);
      const current = await app.screenshot(label);
      if (readFileSync(previous).equals(readFileSync(current))) return current;
      previous = current;
    }
    throw new Error("The viewport did not settle for capture");
  };
  await t3.open();
  await selectRetainedBranch();
  await screen.getByRole("textbox").fill("First unrelated task");
  await screen.getByRole("textbox").press("Enter");
  await browser.locator("text=first fixture turn complete").waitFor({ state: "visible" });
  await screen.getByText("Working", { exact: true }).first().waitFor({ state: "hidden" });
  await refreshStatus();
  await stableCapture("first-new-thread");
  const firstShowsPr = await browser.evaluate(() => document.body.innerText.includes("#33745"));
  await screen.getByRole("button", "New thread").tap();
  await selectRetainedBranch();
  await screen.getByRole("textbox").fill("Second unrelated task");
  await screen.getByRole("textbox").press("Enter");
  await browser.locator("text=first fixture turn complete").waitFor({ state: "visible" });
  await screen.getByText("Working", { exact: true }).first().waitFor({ state: "hidden" });
  await refreshStatus();
  await stableCapture("second-new-thread");
  const secondShowsPr = await browser.evaluate(() => document.body.innerText.includes("#33745"));
  expect([firstShowsPr, secondShowsPr]).toEqual([false, false]);
});
