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

test("Fetched upstream files are excluded from agent changes", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("upstream-demo");
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" });
  const upstream = `${project}-upstream`;
  git(project, "clone", "--quiet", project, upstream);
  git(project, "remote", "add", "upstream", upstream);
  git(project, "fetch", "upstream");
  const thread = await t3.thread({ project, title: "Fetch upstream without edits", messages: ["Establish a clean checkpoint"], model: "multi-turn" });
  writeFileSync(`${upstream}/upstream.txt`, "Published upstream content\n");
  git(upstream, "add", "upstream.txt");
  git(upstream, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Publish upstream file");
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Fetch upstream and fast-forward only. Do not edit files or create commits.");
  await screen.getByRole("textbox").press("Enter");
  const stop = screen.getByRole("button", "Stop generation");
  await expect(stop).toBeVisible();
  git(project, "fetch", "upstream");
  git(project, "merge", "--ff-only", "upstream/main");
  if (git(project, "status", "--porcelain").trim()) throw new Error("Synthetic repository is dirty");
  await expect(stop).toBeHidden({ timeout: 120000 });
  await app.screenshot("upstream-only-turn");
  await expect(screen.getByText("upstream.txt", { exact: true })).toBeHidden();
});
