import { mkdir, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

// Synthetic transcript fixture, matching the reported local-file reproduction.
test("Usage cost labels retain singular and plural token wording", WEB, async ({ t3, app, browser, screen }) => {
  const root = process.env.CLAUDE_CONFIG_DIR!;
  await mkdir(`${root}/projects/-tmp-demo`, { recursive: true });
  const seed = async (n: number) => {
    await writeFile(`${root}/projects/-tmp-demo/s2.jsonl`, JSON.stringify({
      type: "assistant", timestamp: new Date().toISOString(), sessionId: "s2", requestId: `r${n}`,
      message: { id: `m${n}`, model: "claude-mystery-x", usage: { input_tokens: 0, output_tokens: n, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } }
    }) + "\n");
  };
  await seed(1);
  await t3.project("demo");
  const settings = async (patch: object, enable = false) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch, ...(enable ? { providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
      instance: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: {} }
    }} : {}) });
  }).pipe(Effect.scoped));
  await settings({}, true);
  await t3.open("/usage");
  await screen.getByRole("button", "Allow", { exact: true }).click();
  await screen.getByRole("button", "Cost", { exact: true }).click();
  await screen.getByRole("button", "30 days", { exact: true }).click();
  const observed: string[] = [];
  const refresh = async () => {
    await screen.getByRole("button", "Refresh usage", { exact: true }).click();
    await browser.locator('button[aria-label="Refresh usage"][aria-busy="false"]:visible').waitFor();
    await screen.getByRole("button", "claude-mystery-x", { exact: true }).waitFor();
  };
  for (const n of [1, 2]) {
    await seed(n);
    await settings({ usagePriceOverrides: { "claude-mystery-x": null } });
    await refresh();
    await app.screenshot(`provider-${n}-unpriced`);
    observed.push(await browser.evaluate(() => document.body.innerText));
    await screen.getByRole("button", "claude-mystery-x", { exact: true }).click();
    await screen.getByRole("button", "Set price", { exact: true }).waitFor();
    await app.screenshot(`model-${n}-unpriced`);
    observed.push(await browser.evaluate(() => document.body.innerText));
    await browser.keyboard.press("Escape");
    await screen.getByRole("button", "Set price", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot(`return-provider-${n}-unpriced`);
    await settings({ usagePriceOverrides: { "claude-mystery-x": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 4 } } });
    await refresh();
    await app.screenshot(`provider-${n}-priced`);
    observed.push(await browser.evaluate(() => document.body.innerText));
  }
  expect(observed.map((text, i) => text.includes(i < 3 ? (i === 1 ? "1 token has no known price" : "of cost · 1 token") : (i === 4 ? "2 tokens have no known price" : "of cost · 2 tokens")) && (i >= 3 || !text.includes("1 tokens")))).toEqual([true,true,true,true,true,true]);
});
