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

test("Usage counts Pi sessions from the provider instance HOME", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Usage example");
  const instanceHome = path.join(T3_HOME, "instance-home");
  const sessions = path.join(instanceHome, ".pi/agent/sessions/proj");
  await mkdir(sessions, { recursive: true });
  const timestamp = new Date().toISOString();
  await writeFile(path.join(sessions, "s.jsonl"), [
    { type: "session", id: "pi-home-example", timestamp, cwd: "/example" },
    { type: "message", id: "answer", timestamp, message: {
      role: "assistant", provider: "example", model: "example-model",
      usage: { input: 34717, output: 100, cacheRead: 0, cacheWrite: 0, cost: { total: 0 } },
    } },
  ].map((entry) => JSON.stringify(entry)).join("\n") + "\n");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.pi = {
    driver: "pi", enabled: true,
    environment: [{ name: "HOME", value: instanceHome, sensitive: false }],
  };
  await writeFile(settingsPath, JSON.stringify(settings));
  await t3.open();
  await screen.getByText("Usage example", { exact: true }).first().waitFor({ state: "visible" });
  await browser.evaluate(() => {
    localStorage.setItem("t3code:usage-page-preferences:v1", JSON.stringify({
      metric: "tokens", windowDays: 30,
      hiddenProviders: ["codex", "claude", "cursor", "grok", "opencode", "muse", "antigravity"],
    }));
  });
  await app.open("/usage");
  // Wait for the real Usage scan to finish before capturing either side.
  await browser.locator('button[aria-label="Refresh usage"][aria-busy="false"]').first().waitFor({ state: "visible" });
  await browser.locator('[data-slot="skeleton"]').first().waitFor({ state: "hidden" });
  await browser.locator('div[aria-busy="false"]').first().waitFor({ state: "visible" });
  await app.screenshot("pi-instance-home-usage");
  await expect(screen.getByText("34.8K", { exact: true }).first()).toBeVisible();
});
