import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Fork branch compares against the upstream tracked by local main", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Fork comparison", { "README.md": "Fork fixture\n" });
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
  const commit = (name: string) => {
    writeFileSync(join(project, name), `${name}\n`);
    git(project, "add", name);
    git(project, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", name);
  };
  const fork = join(dirname(project), "fork.git");
  const upstream = join(dirname(project), "upstream.git");
  git(project, "clone", "--bare", project, fork);
  git(project, "remote", "add", "origin", fork);
  for (let i = 1; i <= 3; i++) commit(`upstream${i}.txt`);
  git(project, "clone", "--bare", project, upstream);
  git(project, "remote", "add", "upstream", upstream);
  git(project, "fetch", "origin");
  git(project, "fetch", "upstream");
  git(project, "branch", "--set-upstream-to=upstream/main", "main");
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Show the fork branch changes", "--title", "Fork branch", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main", "--branch", "feature/fork-test", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const worktree = git(project, "worktree", "list", "--porcelain").split("\n\n").find(block => block.includes("branch refs/heads/feature/fork-test"))!.split("\n")[0]!.slice(9);
  git(worktree, "config", "--unset", "branch.feature/fork-test.t3-merge-base-ref");
  writeFileSync(join(worktree, "feature.txt"), "Only the feature branch change\n");
  git(worktree, "add", "feature.txt");
  git(worktree, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Add feature");
  await t3.open(thread);
  await screen.getByRole("button", /^Changes vs /).tap();
  await screen.getByRole("button", "Expand feature.txt", { exact: true }).waitFor();
  await screen.getByRole("button", "Refresh diff", { exact: true }).waitFor();
  await screen.getByText("Showing tracked changes. Checking untracked files...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("fork-branch-diff");
  await expect(screen.getByText("upstream/main", { exact: false }).first()).toBeVisible();
  await expect(screen.getByText("upstream1.txt", { exact: false })).not.toBeVisible();
});
