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

const value = Array.from({length:1100}, (_,i)=>String(i+1).padStart(4,"0")).join("-");
const command = `x='${value}'; echo "got=\${#x} want=5499 last=\${x: -4}" | tee result`;
test("First terminal runs the whole long command after slow shell startup", WEB, async ({t3,app,screen,browser})=>{
  await browser.emulateMedia({colorScheme:"dark"});
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(fixture,"utf8");
  const entries = [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"```bash\n"+command+"\n```"}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
  ];
  await writeFile(fixture,entries.map(x=>JSON.stringify(x)).join("\n")+"\n");
  try {
    const project = await t3.project("terminal-demo");
    const thread = await t3.thread({project,title:"Long command",messages:["Show the long Bash command"],model:"command-output"});
    await t3.open(thread);
    await screen.getByRole("button","Run in terminal").tap();
    try {
      await expect.poll(async()=>readFile(`${project}/result`,"utf8").catch(()=>""),{timeout:15000}).toBe("got=5499 want=5499 last=1100\n");
    } finally { await app.screenshot("first-terminal-result"); }
  } finally { await writeFile(fixture,original); }
});
