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

test("Diagnostics rounds 999.6 ms to 1 s", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Duration demo");
  await t3.open("/settings/diagnostics");
  // Synthetic trace input isolates the formatting boundary from wall-clock overhead.
  const now = Date.now();
  const records = [1000, 999.6, 999.371].map((durationMs, index) => JSON.stringify({
    type: "effect-span", name: `DurationSample.${durationMs}ms`,
    traceId: `0000000000000000000000000000000${index}`,
    spanId: `000000000000000${index}`, sampled: true, kind: "internal",
    startTimeUnixNano: String(BigInt(now) * 1000000n),
    endTimeUnixNano: String(BigInt(now) * 1000000n + BigInt(Math.round(durationMs * 1000000))),
    durationMs, attributes: {}, events: [], links: [], exit: { _tag: "Success" },
  }));
  await writeFile(join(T3_HOME, "userdata/logs/server.trace.ndjson"), records.join("\n") + "\n");
  await screen.getByRole("button", "Refresh trace diagnostics").tap();
  await screen.getByText("Slowest Spans", { exact: true }).scrollIntoView();
  await browser.evaluate(() => {
    [...document.querySelectorAll("h1,h2,h3,h4")].find(node => node.textContent === "Slowest Spans")?.scrollIntoView({ block: "start" });
  });
  await app.screenshot("duration-rollover");
  const duration = await browser.evaluate(() => {
    const rows = [...document.querySelectorAll("tr")];
    return rows.find(row => row.cells.length === 4 && row.cells[0]?.textContent === "DurationSample.999.6ms")?.cells[1]?.textContent?.trim();
  });
  expect(duration).toBe("1 s");
});
