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

function number(field: number, value: number): number[] {
  const varint = (n: number) => {
    const bytes: number[] = [];
    do { const byte = n % 128; n = Math.floor(n / 128); bytes.push(byte + (n ? 128 : 0)); } while (n);
    return bytes;
  };
  return [...varint(field * 8), ...varint(value)];
}
function bytes(field: number, value: number[]): number[] {
  const tag = number(field, value.length); tag[0]! += 2; return [...tag, ...value];
}
const text = (field: number, value: string) => bytes(field, [...Buffer.from(value)]);

test("Antigravity Orchestrator names and numeric ID 1537 contribute to estimated cost", WEB,
  async ({ t3, app, screen, browser }) => {
    const root = process.env.ANTIGRAVITY_DATA_DIR!;
    const conversations = path.join(root, "conversations");
    await mkdir(conversations, { recursive: true });
    const db = new DatabaseSync(path.join(conversations, "orchestrator.db"));
    db.exec("DROP TABLE IF EXISTS gen_metadata; DROP TABLE IF EXISTS steps; CREATE TABLE gen_metadata (idx INTEGER, data BLOB); CREATE TABLE steps (idx INTEGER, metadata BLOB)");
    const names = ["gemini-4-neon", "gemini-pro-orchestrator-neon", "gemini-4-hydrogen-orchestrator", "gemini-pro-orchestrator-g1-pro"];
    for (const [idx, name] of names.entries()) {
      db.prepare("INSERT INTO gen_metadata VALUES (?, ?)").run(idx, Buffer.from(bytes(1, text(19, name))));
      db.prepare("INSERT INTO steps VALUES (?, ?)").run(idx, Buffer.from(bytes(9, [...number(2, 1_000_000), ...number(3, 100_000)])));
    }
    db.prepare("INSERT INTO steps VALUES (?, ?)").run(10, Buffer.from(bytes(9, [...number(1, 1537), ...number(2, 1_000_000), ...number(3, 100_000)])));
    db.close();
    // Same synthetic rate table on both commits, using the app's normal on-disk rates cache.
    await writeFile(path.join(T3_HOME, "userdata/usage-model-rates.json"), JSON.stringify({
      fetchedAtMs: Date.now(),
      document: Object.fromEntries(["neon", "hydrogen", "argon"].map(name => [`gemini/gemini-4-${name}`, { input_cost_per_token: 0.000001, output_cost_per_token: 0.000004 }]))
    }));
    await t3.project("Usage pricing demonstration");
    await browser.addInitScript(() => {
      localStorage.setItem("t3code:usage-page-preferences:v1", JSON.stringify({ metric: "cost", windowDays: 30, hiddenProviders: ["codex", "claude", "cursor", "opencode", "grok", "pi", "muse"] }));
    });
    await t3.open("/usage");
    await screen.getByRole("button", "Cost", { exact: true }).tap();
    await screen.getByRole("button", "gemini-pro-orchestrator-neon", { exact: true }).waitFor();
    await browser.locator("table:visible").last().scrollIntoView();
    await app.screenshot("antigravity-cost-breakdown");
    await expect(browser.locator("table:visible").last()).not.toContainText("Unpriced");
    await expect(browser.locator("table:visible").last()).toContainText("$2.80");
  }
);
