import * as fs 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("Interrupted CSI discards leftovers and preserves the next green code", WEB, async ({t3, app, screen, browser}) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await fs.readFile(fixture, "utf8");
  const commands = ["printf 'a\\033[1;\\033[32mb\\033[0m\\n'", "printf 'a\\033[\\033[32mb\\n'"];
  const entries: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt"}}];
  const update = (value: unknown) => entries.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:value}}});
  commands.forEach((command, i) => {
    const output = execFileSync("/bin/bash", ["-lc", command], {encoding:"utf8"});
    update({sessionUpdate:"tool_call",toolCallId:`ansi-${i}`,kind:"execute",title:command,status:"in_progress",rawInput:{command}});
    update({sessionUpdate:"tool_call_update",toolCallId:`ansi-${i}`,status:"completed",rawOutput:output});
  });
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Both ANSI commands finished."}});
  entries.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  try {
    await fs.writeFile(fixture, entries.map(x => JSON.stringify(x)).join("\n")+"\n");
    const project = await t3.project("ansi-demo");
    const thread = await t3.thread({project,title:"Interrupted color codes",messages:["Run the two printf commands."],model:"command-output"});
    await t3.open(thread);
    await screen.getByText("Both ANSI commands finished.").waitFor();
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Ran 2 commands", {exact:false}).tap();
    await screen.getByRole("button", commands[0], {exact:false}).tap();
    await screen.getByRole("button", commands[1], {exact:false}).tap();
    await app.screenshot("expanded-ansi-output");
    const outputs = await browser.evaluate(() => Array.from(document.querySelectorAll("div.max-h-80.overflow-auto.text-muted-foreground")).map(el => ({text:el.textContent?.trim(), green:Array.from(el.querySelectorAll("span")).filter(s => s.textContent === "b").map(s => getComputedStyle(s).color)})));
    expect(outputs).toEqual([{text:"ab",green:["rgb(17, 99, 41)"]},{text:"ab",green:["rgb(17, 99, 41)"]}]);
  } finally {
    await fs.writeFile(fixture, original);
  }
});
