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

test("A working thread protects its shared checkout from another thread's branch picker", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1280, height: 800 });
  const project = await t3.project("Shared checkout", { "file.txt": "main version\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" }).trim();
  git("checkout", "-b", "feature");
  writeFileSync(`${project}/file.txt`, "feature version\n");
  git("add", "file.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Feature version");
  git("checkout", "main");
  const b = await t3.thread({ project, title: "Thread B", messages: ["Ready"] });
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  const frame = (text: string, afterMs: number) => ({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } });
  writeFileSync(fixture, [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    frame("Working in the shared checkout on main. Waiting before reading file.txt again.\n", 0),
    ...Array.from({ length: 120 }, () => frame("", 2000)),
    frame("Finished waiting.\n", 0),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(x => JSON.stringify(x)).join("\n"));
  try {
    const cli = makeState(T3_HOME).cli;
    const a = JSON.parse((await runPromise(cli(["thread", "start", project, "Wait while I check the branch", "--title", "Agent A", "--provider", "devReplay", "--model", "showcase", "--json"]))).stdout);
    await runPromise(cli(["thread", "start", project, "Wait while I check the branch", "--title", "Agent A2", "--provider", "devReplay", "--model", "showcase", "--json"]));
    await t3.open(a);
    await screen.getByRole("button", "Stop generation").waitFor();
    await t3.open(b);
    await screen.getByText("Working", { exact: true }).tap();
    await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
    await screen.getByPlaceholder("Search refs...").fill("feature");
    await screen.getByRole("option", /feature/).first().tap();
    await screen.getByPlaceholder("Search refs...").waitFor({ state: "hidden" });
    // Wait for the real checkout operation to settle through the UI before capturing it.
    await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible:not([disabled])').first().waitFor();
    await new Promise(resolve => setTimeout(resolve, 1000));
    await app.screenshot("branch-switch-while-working");
    expect(git("branch", "--show-current")).toBe("main");
    expect(readFileSync(`${project}/file.txt`, "utf8")).toBe("main version\n");
    await expect(screen.getByText(/Agent A.*still working in this checkout/)).toBeVisible();
  } finally { writeFileSync(fixture, original); }
});
