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

const commands = ["node -pe 'process.version'", "python3 -uc 'print(1)'", "python3 -IBc 'print(1)'", "ruby -ne 'puts $_' /dev/null", "ruby -lane 'puts $F[0]' /dev/null", "node -p 'process.version'", "node -e 'console.log(process.version)'", "python3 -c 'print(1)'", "ruby -e 'puts 1'", "python3 -Wc 'print(1)'", "ruby -ie 'puts 1'"];
test("Bundled inline flags highlight their scripts in the work log", WEB, async ({t3, app, screen, browser}) => {
 const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
 const original = await fs.readFile(fixture, "utf8");
 const rows: unknown[] = [{type:"expect_outbound", frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
 const update = (value: unknown) => rows.push({type:"emit_inbound",afterMs:0,frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:value}}});
 commands.forEach((command, i) => {
  const wrapped = `/bin/bash -lc ${JSON.stringify(command)}`;
  update({sessionUpdate:"tool_call",toolCallId:`cmd-${i}`,kind:"execute",title:wrapped,status:"in_progress",rawInput:{command:wrapped}});
  update({sessionUpdate:"tool_call_update",toolCallId:`cmd-${i}`,status:"completed",rawOutput:i===0 ? "v26.13.1\n" : i===1 || i===2 ? "1\n" : ""});
 });
 update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Command previews ready."}});
 rows.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
 try {
  await fs.writeFile(fixture, rows.map(x=>JSON.stringify(x)).join("\n")+"\n");
  const project = await t3.project("scratch");
  const thread = await t3.thread({project,title:"Inline script previews",model:"command-output",messages:["Run the bundled flags and controls, one command each."]});
  await t3.open(thread);
  await screen.getByText("Command previews ready.",{exact:true}).waitFor();
  await screen.getByRole("button","Worked for",{exact:false}).tap();
  await screen.getByRole("button","Ran 11 commands",{exact:false}).tap();
  const tokens: string[][] = [];
  for (let i=0;i<commands.length;i++) {
   const button = screen.getByRole("button",commands[i],{exact:false}).first();
   await button.tap();
   const wrapped = `/bin/bash -lc ${JSON.stringify(commands[i])}`;
   const read = () => browser.evaluate((command) => {
    const block = Array.from(document.querySelectorAll("div")).find(el => el.className === "text-foreground/85" && el.textContent === command);
    return Array.from(block?.querySelectorAll("span[style]") ?? []).map(s=>s.textContent ?? "");
   }, wrapped);
   await expect.poll(async()=> (await read()).length).toBeGreaterThan(0);
   tokens.push(await read());
   await app.screenshot(`command-${i+1}`);
   await button.tap();
  }
  console.log(JSON.stringify(tokens));
  await expect(tokens.slice(0,5).map((parts,i)=>parts.includes(i===0 ? "process" : i<3 ? "print" : "puts"))).toEqual([true,true,true,true,true]);
  await expect(tokens.slice(9).map(parts=>parts.includes("print") || parts.includes("puts"))).toEqual([false,false]);
 } finally { await fs.writeFile(fixture,original); }
});
