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";

test("Work log unwraps ANSI-C and locale quoted Bash scripts", WEB, async ({t3, app, screen}) => {
  const commands = ["bash -c $'npm test'", 'bash -lc $"npm test"', "bash -c $'echo \\'hi\\'; ls'"];
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  const update = (value: unknown) => frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:value}}});
  commands.forEach((command, i) => {
    update({sessionUpdate:"tool_call",toolCallId:`shell-${i}`,kind:"execute",title:command,status:"in_progress",rawInput:{command}});
    update({sessionUpdate:"tool_call_update",toolCallId:`shell-${i}`,status:"completed",rawOutput:i < 2 ? "tests passed\n" : "hi\npackage.json\n"});
  });
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"done"}});
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  try {
    await fs.writeFile(fixture, frames.map(x => JSON.stringify(x)).join("\n") + "\n");
    const project = await t3.project("shell-label-demo", {"package.json":JSON.stringify({scripts:{test:"echo tests passed"}})});
    const thread = await t3.thread({project,title:"Quoted shell commands",messages:["Run each command in one Bash call: " + commands.join(" ; ")],model:"command-output"});
    await t3.open(thread);
    await screen.getByText("done", {exact:true}).waitFor();
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Ran 3 commands", {exact:false}).tap();
    await app.screenshot("quoted-command-labels");
    await expect(screen.getByRole("button", /^npm test/)).toHaveCount(2);
    await expect(screen.getByRole("button", /^echo 'hi'; ls/)).toHaveCount(1);
  } finally { await fs.writeFile(fixture, original); }
});
