/// <reference lib="dom" />
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

// Use usage counts from an actual repository recording, with synthetic dates and IDs.
// The app's supported price override makes each recorded message cost $0.001.
// Ten messages make the daily peak $0.01; three make the recent hourly peak $0.003.
test("Cost gridlines have distinct whole-cent labels", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Cost chart demo");
  const recording = await readFile(new URL("../../apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/claude_transcript.ndjson", import.meta.url), "utf8");
  const recorded = recording.split("\n").filter(Boolean).map(line => JSON.parse(line)).find(entry => entry.type === "emit_inbound" && entry.frame.type === "assistant").frame.message;
  const home = `${T3_HOME}/recorded-usage`;
  await mkdir(`${home}/projects/demo`, { recursive: true });
  const now = Date.now();
  const rows = [10, 3].flatMap((count, group) => Array.from({ length: count }, (_, index) => ({
    type: "assistant", timestamp: new Date(now - (group === 0 ? 3 * 86400000 : 2 * 3600000)).toISOString(),
    sessionId: `cost-demo-${group}`, requestId: `cost-demo-${group}-${index}`,
    message: { id: `cost-demo-${group}-${index}`, model: recorded.model, usage: recorded.usage },
  })));
  await writeFile(`${home}/projects/demo/session.jsonl`, rows.map(row => JSON.stringify(row)).join("\n") + "\n");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {
      providerInstances: {
        ...Object.fromEntries(["codex", "cursor", "grok", "muse", "pi", "opencode", "antigravity"].map(driver => [driver, { driver, enabled: false, usageAccess: "denied" }])),
        [ProviderInstanceId.make("claudeAgent")]: {
        driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: { homePath: home },
      } },
      usagePriceOverrides: { [recorded.model]: {
        inputCostPerMillionTokens: 0, outputCostPerMillionTokens: 1000 / recorded.usage.output_tokens - 1e-10,
        cacheReadCostPerMillionTokens: 0, cacheWriteCostPerMillionTokens: 0,
      } },
    } });
  }).pipe(Effect.scoped));
  await t3.open("/usage");
  await screen.getByRole("button", "Allow", { exact: true }).click();
  await browser.locator('button').filter({ hasText: /^Cost$/ }).first().click();
  await browser.locator('button').filter({ hasText: /^30 days$/ }).first().click();
  await browser.locator('table caption').filter({ hasText: /^Daily cost by provider$/ }).waitFor({ state: "attached" });
  const labels = () => browser.evaluate(() => {
    const caption = [...document.querySelectorAll("caption")].find(node => /^(Daily|Hourly) cost by provider$/.test(node.textContent ?? ""));
    const chart = caption?.parentElement?.parentElement?.parentElement;
    return [...(chart?.querySelectorAll('div[aria-hidden] > span.absolute') ?? [])].map(node => node.textContent);
  });
  // Wait for the recorded usage to finish loading; no assertion about unrelated UI.
  await browser.locator('td').filter({ hasText: /^\$0\.01$/ }).first().waitFor({ state: "attached" });
  await app.screenshot("daily-cost-one-cent-peak");
  const daily = await labels();
  await browser.locator('button').filter({ hasText: /^Past 24h$/ }).first().click();
  await browser.locator('table caption').filter({ hasText: /^Hourly cost by provider$/ }).waitFor({ state: "attached" });
  await browser.locator('td').filter({ hasText: /^\$0\.00$/ }).first().waitFor({ state: "attached" });
  await app.screenshot("hourly-cost-subcent-peak");
  const hourly = await labels();
  expect({ daily, hourly }).toEqual({ daily: ["0", "$0.01"], hourly: ["0", "$0.01"] });
});
