/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Usage centers legacy Grok provider initials", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Usage alignment");
  const grokHome = path.join(T3_HOME, "synthetic-grok");
  const session = path.join(grokHome, "sessions", "alignment");
  await fs.mkdir(session, { recursive: true });
  await fs.writeFile(path.join(session, "updates.jsonl"), JSON.stringify({
    timestamp: Math.floor(Date.now() / 1000), method: "_x.ai/session/update",
    params: { sessionId: "usage-alignment", update: {
      sessionUpdate: "turn_completed", prompt_id: "prompt-1",
      usage: { inputTokens: 120000, outputTokens: 20000, totalTokens: 140000,
        modelUsage: { "grok-4.5": { inputTokens: 120000, outputTokens: 20000, totalTokens: 140000 } } }
    } }
  }) + "\n");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.grok = { driver: "grok", displayName: "Grok Build (legacy ACP)", enabled: true, usageAccess: "allowed",
    environment: [{ name: "GROK_HOME", value: grokHome, sensitive: false }] };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await t3.open("/usage");
  await screen.getByRole("button", "Tokens", { exact: true }).tap();
  if (await screen.getByRole("button", "Don't allow", { exact: true }).count()) {
    await screen.getByRole("button", "Don't allow", { exact: true }).tap();
  }
  await screen.getByText("140K", { exact: true }).first().waitFor({ timeout: 60000 });
  await screen.getByText("GB", { exact: true }).first().waitFor();
  await browser.evaluate(async () => { await document.fonts.ready; return null; });
  await app.screenshot("usage-provider-initials");
  const offsets = await browser.evaluate(() => [...document.querySelectorAll("span")]
    .filter(el => el.textContent === "GB" && el.childElementCount === 0)
    .map(el => {
      const box = el.getBoundingClientRect();
      const range = document.createRange(); range.selectNodeContents(el);
      const glyph = range.getBoundingClientRect();
      return { size: box.width, vertical: glyph.y + glyph.height / 2 - box.y - box.height / 2,
        horizontal: glyph.x + glyph.width / 2 - box.x - box.width / 2 };
    }));
  console.log("Initials offsets", JSON.stringify(offsets));
  expect(offsets.length).toBeGreaterThan(0);
  for (const offset of offsets) {
    expect(Math.abs(offset.vertical), `Glyph center in ${offset.size}px icon`).toBeLessThanOrEqual(1);
    expect(Math.abs(offset.horizontal)).toBeLessThanOrEqual(1);
  }
});
