import { createServer } from "node:http";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { IOS, test } from "./t3-mobile.ts";
import { rpcClient, runPromise } from "./t3.ts";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";

test("Pooled usage speaks singular for one reset credit, with and without reset time", IOS, async ({ t3, app, screen }) => {
  const hub = createServer(async (req, res) => {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const body = raw ? JSON.parse(raw) : {};
    const index = Number(body.auth_index ?? 0);
    const accounts = [1, 2, 1, 2];
    let result: unknown;
    if (req.url?.endsWith("/auth-files")) result = { files: accounts.map((_, i) => ({ id: `account-${i}.json`, auth_index: String(i), provider: "codex", email: `${i % 2 ? "two" : "one"}${i}@example.invalid`, id_token: { chatgpt_account_id: `account-${i}` } })) };
    else if (body.url?.endsWith("/rate-limit-reset-credits")) result = { status_code: 200, body: JSON.stringify({ credits: Array.from({length: accounts[index]}, (_, i) => ({id: `credit-${index}-${i}`, status: "available", reset_type: "codex_rate_limits", expires_at: "2099-01-01T00:00:00Z"})) }) };
    else if (body.url?.endsWith("/usage")) result = { status_code: 200, body: JSON.stringify({plan_type: "pro", rate_limit: {primary_window: {used_percent: 40, reset_at: index < 2 ? Math.floor(Date.now()/1000) + (index + 2)*3600 : null, limit_window_seconds: 18000}}}) };
    else { res.writeHead(404); res.end("{}"); return; }
    res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(result));
  });
  await new Promise<void>(resolve => hub.listen(13996, "127.0.0.1", resolve));
  try {
    const project = await t3.project("Usage demo");
    await t3.thread({project, title: "Usage evidence", messages: ["first"]});
    await runPromise(Effect.scoped(Effect.gen(function* () {
      const rpc = yield* rpcClient(MOBILE_T3_HOME, `http://127.0.0.1:${MOBILE.serverPort}`);
      yield* rpc["server.updateSettings"]({patch: {usageLimitSources: {proof: {kind: "cliproxy", label: "Usage demo", url: "http://127.0.0.1:13996", managementKey: "synthetic-key", enabled: true}}}});
    })));
    await t3.open();
    await screen.getByText("Usage", {exact: true}).tap({timeout: 120_000});
    await screen.getByText("Limits", {exact: true}).tap();
    // Capture the rendered pool before asserting its spoken accessibility labels.
    await screen.getByText("Session", {exact: true}).waitFor({state: "visible", timeout: 120_000});
    await app.screenshot("pooled-session-reset-credits");
    console.log("SPOKEN_LABELS\n" + (await screen.tree()).split("\n").filter(line => line.includes("reset credit")).join("\n"));
    await expect(screen.getByText("1 reset credit banked", {exact: false}).first()).toBeVisible();
    await expect(screen.getByText("1 reset credit banked", {exact: false}).nth(1)).toBeVisible();
    await expect(screen.getByText("2 reset credits banked", {exact: false}).first()).toBeVisible();
    await expect(screen.getByText("2 reset credits banked", {exact: false}).nth(1)).toBeVisible();
  } finally { await new Promise<void>((resolve, reject) => hub.close(error => error ? reject(error) : resolve())); }
});
