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

const outputs = [
  ["Get order", '{"guild_id":1234567890123456789,"order_id":9007199254740993,"overflow":1e309}'],
  ["List orders ndjson", '{"id":1}\n{"id":-9007199254740993}'],
  ["Get small", '{"id":42}'],
];

test("Tool JSON preserves large integers and overflow tokens", WEB, async ({t3, app, screen, browser}) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  const emit = (update: unknown) => frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update}}});
  for (const [index, [title, text]] of outputs.entries()) {
    emit({sessionUpdate:"tool_call",toolCallId:`orders-${index}`,kind:"other",title,status:"in_progress",rawInput:{}});
    emit({sessionUpdate:"tool_call_update",toolCallId:`orders-${index}`,status:"completed",rawOutput:{content:[{type:"text",text}]}});
  }
  emit({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"done"}});
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  await writeFile(fixture, frames.map(f => JSON.stringify(f)).join("\n"));
  try {
    const project = await t3.project("Orders demo");
    const thread = await t3.thread({project,title:"Exact order IDs",messages:["Call get_order, list_orders_ndjson, then get_small."],model:"command-output"});
    await t3.open(thread);
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Used 3 tools", {exact:false}).tap();
    for (const [title] of outputs) await screen.getByRole("button",title,{exact:false}).tap();
    await app.screenshot("tool-json-values");
    await browser.evaluate(() => {
      const blocks = document.querySelectorAll("pre");
      const range = document.createRange();
      range.setStartBefore(blocks[0]!);
      range.setEndAfter(blocks[blocks.length - 1]!);
      window.getSelection()?.removeAllRanges();
      window.getSelection()?.addRange(range);
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+C");
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await browser.keyboard.press("ControlOrMeta+Home");
    await app.screenshot("copied-tool-json");
    await expect(composer).toContainText("1234567890123456789");
    await expect(composer).toContainText("9007199254740993");
    await expect(composer).toContainText("1e309");
    await expect(composer).toContainText("-9007199254740993");
    await expect(screen.getByText("1234567890123456789",{exact:false}).first()).toBeVisible();
    await expect(screen.getByText("9007199254740993",{exact:false}).first()).toBeVisible();
    await expect(screen.getByText("1e309",{exact:false}).first()).toBeVisible();
    await expect(screen.getByText("-9007199254740993",{exact:false}).first()).toBeVisible();
  } finally { await writeFile(fixture, original); }
});
