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("Live shell labels preserve hashes inside parameter expansions", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const records: unknown[] = [];
  const prompt = () => records.push({type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}});
  const update = (value: unknown, afterMs = 250) => records.push({type:"emit_inbound",afterMs,frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:value}}});
  const end = () => records.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  prompt(); update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Ready to inspect shell command labels."}}); end();
  const commands = ["echo ${a:- #1}", "x=${a:- #1}; git status", "echo hi # ${a}", "echo ${a:- #1} # real comment"];
  for (const command of commands) {
    prompt();
    update({sessionUpdate:"tool_call",toolCallId:"shell",kind:"execute",title:"Shell",status:"in_progress",rawInput:{command}});
    for (let i = 0; i < 90; i++) update({sessionUpdate:"tool_call_update",toolCallId:"shell",status:"in_progress"}, 2000);
    end();
  }
  await writeFile(fixture, records.map(x => JSON.stringify(x)).join("\n") + "\n");
  try {
    const project = await t3.project("shell-label-demo");
    await t3.open();
    await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
    await screen.getByRole("option", "Showcase", {exact:false}).waitFor();
    await browser.keyboard.press("Escape");
    const thread = await t3.thread({project,title:"Shell parameter expansion labels",messages:["Prepare the command label demonstration"],model:"showcase"});
    await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
    await t3.open(thread);
    const labels: string[] = [];
    for (const [index, command] of commands.entries()) {
      const composer = screen.getByRole("textbox");
      await composer.fill(`Inspect command: ${command}`);
      await composer.press("Enter");
      const row = screen.getByRole("button", /^Running (command|echo|git)/).last();
      await row.waitFor();
      labels.push((await row.textContent()) ?? "");
      await row.tap();
      await screen.getByText(command, {exact:true}).last().waitFor();
      await app.screenshot(`command-${index + 1}-expanded`);
      await screen.getByRole("button", "Stop generation").tap();
      await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
    }
    expect(labels.map(label => label.match(/Running (command|echo|git)/)?.[0])).toEqual(["Running echo", "Running git", "Running echo", "Running echo"]);
  } finally { await writeFile(fixture, original); }
});
