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

// Uses existing public fork PRs; no forge writes or mocked provider responses.
test("Fork branches use their own published PR and unpublished branches inherit none", WEB, async ({ t3, app, screen }) => {
  const configure = async (title: string, fork: string, branch: string, published: boolean) => {
    const project = await t3.project(title);
    const git = (...args: string[]) => execFileSync("git", args, { cwd: project, stdio: "pipe" });
    git("remote", "add", "origin", `https://github.com/${fork}/t3code.git`);
    git("remote", "add", "upstream", "https://github.com/pingdotgg/t3code.git");
    git("config", "remote.upstream.gh-resolved", "base");
    git("fetch", "--depth=1", "origin", "main:refs/remotes/origin/main", ...(published ? [`${branch}:refs/remotes/origin/${branch}`] : []));
    git("remote", "set-head", "origin", "main");
    git("checkout", "--force", "-b", branch, "--track", "origin/main");
    if (published) git("reset", "--hard", `origin/${branch}`);
    return await t3.thread({ project, title, messages: ["Show the current branch without changing files."] });
  };
  const published = await configure("Published fork feature", "exherb", "fix/fork-pr-head", true);
  const unpublished = await configure("Unpublished fork feature", "AdarshMund-dev", "feature/unpublished-proof", false);
  await t3.open(unpublished);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor({ timeout: 60000 });
  await screen.getByRole("button", /^Changes /).waitFor({ timeout: 60000 });
  await screen.getByText(/^Syncing messages/).waitFor({ state: "hidden", timeout: 60000 });
  await app.screenshot("unpublished-branch");
  await t3.open(published);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor({ timeout: 60000 });
  await screen.getByRole("button", /^Changes /).waitFor({ timeout: 60000 });
  await screen.getByText(/^Syncing messages/).waitFor({ state: "hidden", timeout: 60000 });
  try {
    await expect(screen.getByRole("link", /^PR #32262/).first()).toBeVisible({ timeout: 60000 });
  } finally {
    await app.screenshot("published-branch");
  }
  await t3.open(unpublished);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor({ timeout: 60000 });
  await expect(screen.getByRole("link", /^PR #35795/)).not.toBeVisible();
});
