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

test("Latest turn follows completions while an explicit turn stays pinned", WEB, async ({t3, app, screen, browser}) => {
  const sha = execFileSync("git", ["rev-parse", "--short=10", "HEAD"], {cwd: APP_DIR, encoding:"utf8"}).trim();
  const project = await t3.project(`Diff proof ${sha}`);
  const thread = await t3.thread({project, title:`Latest turn proof ${sha}`, messages:["Prepare the review"], model:"showcase"});
  await t3.open(thread);
  const stop = screen.getByRole("button", "Stop generation");
  async function turn(file: string) {
    await screen.getByRole("textbox").fill(`Record ${file}`);
    await screen.getByRole("textbox").press("Enter");
    await stop.waitFor({state:"visible"});
    // The page is already loaded; a streamed tool marks provider startup and baseline capture.
    await screen.getByText("The project has a single math module", {exact:false}).last().waitFor({state:"visible"});
    await writeFile(`${project}/${file}`, `Change recorded in ${file}\n`);
    await stop.waitFor({state:"hidden", timeout:60000});
    await screen.getByText(file, {exact:true}).first().waitFor({state:"visible"});
  }
  await turn("one.txt");
  await browser.keyboard.press("Control+d");
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitemradio", "Latest turn", {exact:true}).tap();
  await screen.getByRole("button", /^(Expand|Collapse) one\.txt$/).waitFor({state:"visible"});
  await app.screenshot("latest-before-next-turn");
  await turn("two.txt");
  await screen.getByRole("status", "Loading checkpoint diff...").waitFor({state:"hidden"});
  await app.screenshot("latest-after-next-turn");
  await expect.soft(screen.getByRole("button", "Diff scope: Latest turn", {exact:true})).toBeVisible();
  await expect.soft(screen.getByRole("button", /^(Expand|Collapse) two\.txt$/)).toBeVisible();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitem", "Turn", {exact:true}).hover();
  await screen.getByRole("menuitemradio", /^Turn 3/).tap();
  await screen.getByRole("button", /^(Expand|Collapse) two\.txt$/).waitFor({state:"visible"});
  await app.screenshot("explicit-newest-turn-selected");
  await expect.soft(screen.getByRole("button", "Diff scope: Turn 3", {exact:true})).toBeVisible();
  await turn("three.txt");
  await app.screenshot("explicit-turn-stays-pinned-after-completion");
  await expect.soft(screen.getByRole("button", "Diff scope: Turn 3", {exact:true})).toBeVisible();
  await expect.soft(screen.getByRole("button", /^(Expand|Collapse) two\.txt$/)).toBeVisible();
});
