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

// Read-only public release history: main is default; dev's release PR is merged.
const repository = "https://github.com/Jamie-Fairweather/t3code.git";

test("An unpublished worktree based on dev has no release PR badge", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Release workflow");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("remote", "add", "origin", repository);
  // Keep the real commit identities, with only the README checked out.
  git("config", "remote.origin.promisor", "true");
  git("config", "remote.origin.partialclonefilter", "blob:none");
  git("fetch", "--depth=1", "--filter=blob:none", "origin", "main:refs/remotes/origin/main", "dev:refs/remotes/origin/dev");
  git("sparse-checkout", "set", "--no-cone", "/README.md");
  git("reset", "--hard", "origin/main");
  git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
  git("branch", "dev", "origin/dev");
  const { cli } = makeState(T3_HOME);
  const launched = await runPromise(cli([
    "thread", "start", project, "Describe this workspace", "--title", "Unpublished feature from dev",
    "--worktree", "origin/dev", "--branch", "feature/unpublished-from-dev",
    "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json",
  ]));
  const { threadId } = JSON.parse(launched.stdout);
  const branch = "feature/unpublished-from-dev";
  const upstream = git("for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`);
  const base = git("config", "--get", `branch.${branch}.t3-merge-base`);
  if (upstream !== "origin/dev" || base !== "dev") throw new Error(`Unexpected branch setup: ${upstream}, ${base}`);
  // Also exercise the compatibility key from the report, without replacing T3's current key.
  git("config", `branch.${branch}.gh-merge-base`, "dev");
  await t3.open();
  await screen.getByTestId("sidebar-row-card").tap();
  await browser.evaluate(() => new Promise<void>((resolve) => {
    const ready = () => {
      const text = document.body.innerText;
      return text.includes("first fixture turn complete") &&
        !text.includes("Loading messages") && !text.includes("Syncing messages");
    };
    const observer = new MutationObserver(() => {
      if (ready()) { observer.disconnect(); resolve(); }
    });
    observer.observe(document.body, { childList: true, subtree: true, characterData: true });
    if (ready()) { observer.disconnect(); resolve(); }
  }));
  // Opening Git action options requests fresh repository status.
  await screen.getByRole("button", "Git action options", { exact: true }).tap();
  await browser.keyboard.press("Escape");

  await app.screenshot("thread-details");
  await screen.getByRole("button", "Toggle thread details panel").tap();
  await app.screenshot("unpublished-feature");
  await expect(screen.getByRole("link", /PR #15/)).toHaveCount(0);
});
