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

test("Turn diffs use the destination branch after a branch switch", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("branch-switch-demo", { "shared.txt": "base\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project });
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  git("branch", "B");
  git("switch", "-c", "A");
  // Give the replay model real, deterministic workspace actions inside each live turn.
  // Only the dev replay agent changes; checkpointing and diff production remain the app's.
  const replayPath = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  const original = readFileSync(replayPath, "utf8");
  const actions = `
    if (session.cwd.endsWith("/branch-switch-demo")) {
      const git = (...args: string[]) => scenarioExec("git", args, { cwd: session.cwd });
      if (session.promptCount === 1) {
        NodeFS.writeFileSync(session.cwd + "/shared.txt", "A content\\n");
        NodeFS.writeFileSync(session.cwd + "/a.txt", "A only\\n");
        git("add", "shared.txt", "a.txt");
        git("commit", "-m", "A changes");
      } else {
        git("switch", "B");
        NodeFS.writeFileSync(session.cwd + "/shared.txt", "B edit\\n");
        NodeFS.writeFileSync(session.cwd + "/b.txt", "B only\\n");
      }
    }
  `;
  writeFileSync(replayPath, original.replace('#!/usr/bin/env node', '#!/usr/bin/env node\nimport { execFileSync as scenarioExec } from "node:child_process";').replace('const session = sessions.get(sessionId)!;', 'const session = sessions.get(sessionId)!;' + actions));
  let thread;
  try {
    thread = await t3.thread({ project, title: "Branch switch diff", model: "multi-turn", messages: [
      "On A, change shared.txt to A content, add a.txt, and commit both.",
      "Switch to B, change shared.txt to B edit, and create b.txt."
    ] });
  } finally {
    writeFileSync(replayPath, original);
  }
  await t3.open(thread);
  await screen.getByRole("button", "Open diff", { exact: true }).last().tap();
  await screen.getByRole("button", "Expand shared.txt", { exact: true }).tap();
  await screen.getByText("B edit", { exact: true }).waitFor({ state: "visible", timeout: 60000 });
  await app.screenshot("branch-B-turn-diff");
  await expect(screen.getByText("base", { exact: true })).toBeVisible();
  await expect(screen.getByText("A content", { exact: true })).toBeHidden();
  await expect(screen.getByRole("button", "Collapse a.txt", { exact: true })).toBeHidden();
  await expect(screen.getByRole("region", "Workspace panel: Diff").getByText("b.txt", { exact: true })).toBeVisible();
});
