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 quote = '{"price":123456789012345.6789,"ratio":0.1000000000000000000001}';

test("Expanded quote tool output preserves exact decimal values", WEB, async ({ t3, app, screen }) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: value } } });
  const transcript = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "quote", kind: "other", title: "Get Quote", status: "in_progress", rawInput: { symbol: "ACME" } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "quote", status: "completed", rawOutput: { content: [{ type: "text", text: quote }] } }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(entry => JSON.stringify(entry)).join("\n");
  try {
    await fs.writeFile(fixture, transcript);
    const project = await t3.project("quote-demo");
    const thread = await t3.thread({ project, title: "Exact decimal quote", messages: ["Call get_quote with symbol ACME exactly once, then reply done."], model: "default" });
    await t3.open(thread);
    await screen.getByText("done", { exact: true }).waitFor();
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Get Quote", { exact: false }).tap();
    await app.screenshot("expanded-quote-decimals");
    await expect(screen.getByText(quote, { exact: false })).toBeVisible();
  } finally {
    await fs.writeFile(fixture, original);
  }
});
