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

test("Edited queued messages honor alternate steering and plain save", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("queued-message-demo");
  const thread = await t3.thread({project, title: "Queued message steering", messages: ["Prepare the demo"]});
  // A long synthetic replay keeps the real turn running throughout the four interactions.
  const recording = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await readFile(recording, "utf8");
  const frames: object[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt"}}];
  const update = (value: object, afterMs = 0) => ({type:"emit_inbound",afterMs,frame:{kind:"notification",method:"session/update",params:{sessionId:"demo",update:value}}});
  frames.push(update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"I am working on the demo. You can edit and steer queued follow-ups while this turn runs."}}));
  frames.push(update({sessionUpdate:"tool_call",toolCallId:"demo-work",kind:"execute",title:"Long-running demo task",status:"in_progress"}));
  for(let i=0;i<120;i++) frames.push(update({sessionUpdate:"tool_call_update",toolCallId:"demo-work",status:"in_progress"},2000));
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  await writeFile(recording, frames.map(f=>JSON.stringify(f)).join("\n")+"\n");
  try {
    await t3.open("/settings/chat");
    await screen.getByRole("combobox", "Follow-up behavior").tap();
    await screen.getByRole("option", "Queue", {exact:true}).tap();
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    await composer.fill("Run the long demo task");
    await composer.press("Enter");
    await screen.getByText("I am working on the demo.", {exact:false}).waitFor();
    const remainsQueued: boolean[] = [];
    for (const mode of ["plain-enter", "plain-click", "ctrl-click", "ctrl-enter"]) {
      await composer.fill(`Original follow-up for ${mode}`);
      await composer.press("Enter");
      await browser.locator('[data-thread-queue] li').filter({hasText:`Original follow-up for ${mode}`}).getByRole("button", "Edit queued message").tap();
      const edited = `Edited follow-up for ${mode}`;
      await composer.fill(edited);
      await app.screenshot(`${mode}-editing`);
      if(mode === "plain-enter") await composer.press("Enter");
      if(mode === "plain-click") await screen.getByRole("button", "Update queued message").tap();
      if(mode === "ctrl-click") await screen.getByRole("button", "Update queued message").tap({modifiers:["Control"]});
      if(mode === "ctrl-enter") await composer.press("Control+Enter");
      await screen.getByRole("button", "Update queued message").waitFor({state:"hidden"});
      await screen.getByText(edited, {exact:true}).first().waitFor();
      // Allow the persisted edit and subsequent promotion to settle before the capture.
      await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 600)));
      await app.screenshot(`${mode}-result`);
      remainsQueued.push(await browser.locator('[data-thread-queue] li').filter({hasText:edited}).isVisible());
      if (mode.startsWith("plain")) {
        await browser.locator('[data-thread-queue] li').filter({hasText:edited}).getByRole("button", "Remove queued message").tap();
        await browser.locator('[data-thread-queue] li').filter({hasText:edited}).waitFor({state:"hidden"});
      }
    }
    await app.screenshot("final-queue");
    await expect(remainsQueued).toEqual([true,true,false,false]);
    await screen.getByRole("button", "Stop generation").tap();
  } finally {
    await writeFile(recording, original);
  }
});
