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

const varint = (n: number): number[] => {
  const bytes: number[] = [];
  while (n > 127) { bytes.push((n % 128) | 128); n = Math.floor(n / 128); }
  return [...bytes, n];
};
test("Removed Antigravity profile history stays in Usage", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("usage-demo");
  const thread = await t3.thread({ project, title: "Usage history", messages: ["Hello"] });
  await t3.open(thread);
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances["antigravity-2"] = { driver: "antigravity", enabled: false, config: { authMethod: "gemini-api-key" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const dir = path.join(T3_HOME, "userdata/providers/antigravity", createHash("sha256").update("antigravity-2").digest("hex"), "antigravity-acp/conversations");
  await fs.mkdir(dir, { recursive: true });
  const db = new DatabaseSync(path.join(dir, "repro.db"));
  db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)");
  const tokens = [0x10, ...varint(123456), 0x18, ...varint(4242)];
  const timestamp = [0x08, ...varint(Math.floor(Date.now() / 1000) - 3600)];
  db.prepare("INSERT INTO steps VALUES (?, ?)").run(0, new Uint8Array([0x4a, tokens.length, ...tokens, 0x42, timestamp.length, ...timestamp]));
  db.close();
  await t3.open("/usage");
  await screen.getByRole("button", "Tokens", { exact: true }).tap();
  await screen.getByText("antigravity-unknown", { exact: true }).waitFor({ timeout: 60000 });
  await app.screenshot("configured-profile-history");
  delete settings.providerInstances["antigravity-2"];
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await t3.open(thread);
  await t3.open("/usage");
  await screen.getByRole("button", "Refresh usage", { exact: true }).click();
  await browser.locator('button[aria-label="Refresh usage"][aria-busy="false"]:visible').waitFor();
  try {
    await expect(screen.getByText("antigravity-unknown", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("removed-profile-history");
  }
});
