import { ProviderDriverKind, ProviderInstanceId } 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";

test("Pi usage discovers real history in a directory ending in a space", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    for (const driver of ["claude", "codex", "pi"]) {
      yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId: ProviderInstanceId.make(driver), instance: {
          driver: ProviderDriverKind.make(driver), enabled: driver === "pi", usageAccess: driver === "pi" ? "allowed" : "denied",
          ...(driver === "pi" ? { environment: [{ name: "PI_CODING_AGENT_SESSION_DIR", value: process.env.PI_PROOF_SESSION_DIR!, sensitive: true }] } : {})
        }
      }});
    }
  }).pipe(Effect.scoped));
  await t3.open("/usage");
  await screen.getByRole("button", "Tokens", { exact: true }).tap();
  await screen.getByRole("button", "30 days", { exact: true }).tap();
  const refresh = browser.locator('button[aria-label="Refresh usage"]:visible');
  await refresh.click();
  await browser.locator('button[aria-label="Refresh usage"][aria-busy="false"]:visible').waitFor();
  await browser.locator('div[aria-busy="false"]').first().waitFor();
  await app.screenshot("pi-usage-trailing-space");
  await expect(screen.getByText("1 session", { exact: true }).first()).toBeVisible();
});
