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 outputs = ['{"total":2,"1":"a","0":"b"}', '{"10":1,"9":2}', '{"2":1,"10":2,"a":3}'];

test("Expanded tool JSON preserves returned key order and still formats ordered JSON", WEB, async ({t3, app, screen, browser}) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt"}}];
  for (const [i, text] of outputs.entries()) {
    const update = (value: unknown) => ({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:value}}});
    frames.push(update({sessionUpdate:"tool_call",toolCallId:`read-${i}`,kind:"read",title:`Read case ${i+1}`,status:"pending"}));
    frames.push(update({sessionUpdate:"tool_call_update",toolCallId:`read-${i}`,status:"completed",content:[{type:"content",content:{type:"text",text}}]}));
  }
  frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:'Returned tool text: '+outputs.join(' | ')}}}}});
  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("demo");
    const thread = await t3.thread({project,title:"Tool JSON key order",messages:["Read the three JSON cases"],model:"showcase"});
    await t3.open(thread);
    await screen.getByText("Returned tool text:", {exact:false}).waitFor({timeout:60000});
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Read 3 files").tap();
    const rows = screen.getByRole("button", "Read file", {exact:false});
    await rows.nth(0).tap();
    await rows.nth(1).tap();
    await rows.nth(2).tap();
    await app.screenshot("expanded-tool-json");
    const displayed = await browser.evaluate(() => Array.from(document.querySelectorAll("pre"), node => node.textContent ?? ""));
    expect(displayed).toContain(outputs[0]);
    expect(displayed).toContain(outputs[1]);
    expect(displayed).toContain(JSON.stringify(JSON.parse(outputs[2]!), null, 2));
  } finally { await fs.writeFile(fixture, original); }
});
