import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "A provider's token share follows the Usage page language",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("usage-demo");
    const seed = async (boundary = false) => { await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const timestamp = DateTime.formatIso(yield* DateTime.now);
        const piSessions = path.join(T3_HOME, "pi-history");
        const codexHome = path.join(T3_HOME, "usage-codex");
        const codexSessions = path.join(codexHome, "sessions");
        const jsonLines = (entries: readonly unknown[]) =>
          entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
        yield* fs.makeDirectory(piSessions, { recursive: true });
        yield* fs.makeDirectory(codexSessions, { recursive: true });
        yield* fs.writeFileString(
          path.join(piSessions, "session.jsonl"),
          jsonLines([
            { type: "session", version: 3, id: "demo", timestamp, cwd: project },
            {
              type: "message",
              id: "reply",
              parentId: null,
              timestamp,
              message: {
                role: "assistant",
                provider: "anthropic",
                model: "fixture-model",
                usage: { input: 100, cost: { total: 0.02 } },
              },
            },
          ]),
        );
        yield* fs.writeFileString(
          path.join(codexSessions, "rollout.jsonl"),
          jsonLines([
            { type: "session_meta", timestamp, payload: { id: "demo" } },
            { type: "turn_context", timestamp, payload: { model: "gpt-6.2-sol" } },
            {
              type: "event_msg",
              timestamp,
              payload: {
                type: "token_count",
                info: { last_token_usage: { input_tokens: boundary ? 199999 : 700, output_tokens: 0 } },
              },
            },
          ]),
        );
        if (boundary) yield* fs.writeFileString(
          path.join(codexSessions, "unpriced.jsonl"),
          jsonLines([
            { type: "session_meta", timestamp, payload: { id: "unpriced" } },
            { type: "turn_context", timestamp, payload: { model: "unknown-usage-model" } },
            { type: "event_msg", timestamp, payload: { type: "token_count", info: { last_token_usage: { input_tokens: 1, output_tokens: 0 } } } },
          ]),
        );
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        const binaryPath = path.join(T3_HOME, "bin", "no-model");
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("pi"),
            instance: {
              driver: ProviderDriverKind.make("pi"),
              enabled: true,
              usageAccess: "allowed",
              config: { binaryPath },
              environment: [
                { name: "PI_CODING_AGENT_SESSION_DIR", value: piSessions, sensitive: false },
              ],
            },
          },
        });
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("usage-codex"),
            instance: {
              driver: ProviderDriverKind.make("codex"),
              enabled: true,
              usageAccess: "allowed",
              config: { setupMode: "existing", binaryPath, homePath: codexHome },
            },
          },
        });
      }).pipe(Effect.scoped),
    );
    };
    await seed();
    await t3.open("/settings/general");
    await screen.getByLabel("Language", { exact: true }).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1800));
    await screen.getByLabel("Language", { exact: true }).tap();
    await new Promise((resolve) => setTimeout(resolve, 1200));
    await screen.getByText("Français", { exact: true }).tap();
    await screen.getByLabel("Langue", { exact: true }).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await t3.open("/usage");
    const usage = screen.getByRole("dialog", "Utilisation");
    await usage.getByRole("button", "Tokens", { exact: true }).tap();
    const share = usage.getByText(/^12[.,]5\s?% des tokens · 0,02\s?\$/);
    await share.waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("provider-token-share-in-french");
    await browser.locator('div[aria-hidden="true"].h-2 > div').first().hover();
    await screen.getByText(/^Entrée · 800 · 100[.,]0\s?%$/).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 600));
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("token-type-share-tooltip-in-french");
    await usage.getByText("anthropic/fixture-model", { exact: true }).tap();
    await screen.getByRole("dialog", "anthropic/fixture-model").waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("model-dialog-in-french");
    await browser.keyboard.press("Escape");
    await seed(true);
    await t3.open("/usage");
    await screen.getByRole("button", "Actualiser l’utilisation", { exact: true }).tap();
    await usage.getByRole("button", "Tokens", { exact: true }).tap();
    const boundary = usage.getByText(/^<0[.,]1\s?% des tokens/);
    await boundary.waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("boundary-token-shares-in-french");
    await usage.getByRole("button", "Coût", { exact: true }).tap();
    await usage.getByRole("button", "Détails de l’utilisation sans prix", { exact: true }).tap();
    await screen.getByText(/L’estimation API exclut/).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 600));
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("unpriced-records-tooltip-in-french");
    await browser.keyboard.press("Escape");
    await usage.getByRole("button", "Tokens", { exact: true }).tap();
    await t3.open("/settings/general");
    await screen.getByLabel("Langue", { exact: true }).tap();
    await screen.getByText("English", { exact: true }).tap();
    await t3.open("/usage");
    await screen.getByText(/^<0\.1% of tokens/).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await app.screenshot("boundary-token-shares-in-english");
    await t3.open("/settings/general");
    await screen.getByLabel("Language", { exact: true }).tap();
    await screen.getByText("Français", { exact: true }).tap();
    await t3.open("/usage");
    await expect(boundary).toHaveText(/^<0,1\s% des tokens/);
  },
);
