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 { MOBILE_T3_HOME as T3_HOME, MOBILE } from "../e2e.config.ts";
import { rpcClient, runPromise } from "./t3.ts";

import { IOS, test } from "./t3-mobile.ts";

test(
  "Mobile Usage costs and session counts follow Deutsch",
  IOS,
  async ({ t3, app, screen, device }) => {
    const project = await t3.project("demo");
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const sessionDir = path.join(T3_HOME, "pi-history");
        const timestamp = new Date().toISOString();
        yield* fs.makeDirectory(sessionDir, { recursive: true });
        for (let i = 0; i < 1234; i++) {
          yield* fs.writeFileString(path.join(sessionDir, `session-${i}.jsonl`), [
            { type: "session", version: 3, id: `synthetic-${i}`, timestamp, cwd: project },
            { type: "message", id: `message-${i}`, parentId: null, timestamp,
              message: { role: "assistant", provider: "anthropic", model: "claude-sonnet-4-5",
                usage: { input: 42, cost: { total: 0.02 / 1234 } } } }
          ].map(entry => JSON.stringify(entry)).join("\n") + "\n");
        }
        const client = yield* rpcClient(T3_HOME, `http://${MOBILE.host}:${MOBILE.serverPort}`);
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("pi"),
            instance: {
              driver: ProviderDriverKind.make("pi"),
              enabled: true,
              usageAccess: "allowed",
              config: {
                binaryPath: path.join(T3_HOME, "bin", "no-model"),
                launchArgs: "--session-dir " + sessionDir.replaceAll(" ", "\\ "),
              },
              environment: [
                { name: "PI_CODING_AGENT_SESSION_DIR", value: sessionDir, sensitive: false },
              ],
            },
          },
        });
      }).pipe(Effect.scoped),
    );

    await t3.open();
    await screen.getByText("demo", { exact: false }).first().waitFor({ timeout: 240_000 });
    await device.openLink("t3code-dev://settings/language", { app: "com.t3tools.t3code.dev" });
    await device.alert("accept").catch(() => {});
    await screen.getByText("Deutsch", { exact: true }).tap();
    await screen.getByText("Sprache", { exact: true }).first().waitFor();
    await device.openLink("t3code-dev://settings/usage?tab=usage", { app: "com.t3tools.t3code.dev" });
    await device.alert("accept").catch(() => {});
    await screen.getByText("Rohe Token-Kosten", { exact: true }).waitFor();
    await screen.getByText("Pi", { exact: true }).first().waitFor();
    await app.screenshot("german-costs");
    await expect(screen.getByText(/0,02\s*\$\*/)).toBeVisible();
    await screen.getByText("Tokens", { exact: true }).tap();
    await app.screenshot("german-session-count");
    await expect(screen.getByText("Über 1.234 Sitzungen", { exact: true })).toBeVisible();
  },
);
