import { createServer } from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Pooled Codex limits weight Pro 20x against Plus", WEB, async ({ t3, app, screen, browser }) => {
  const now = Date.now();
  const accounts = { pro20x: { plan: "pro", used: 100 }, plus: { plan: "plus", used: 0 } };
  const hub = createServer((request, response) => {
    let raw = "";
    request.on("data", chunk => { raw += chunk; });
    request.on("end", () => {
      const json = (body: unknown) => { response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify(body)); };
      if (request.url?.endsWith("/auth-files")) return json({ files: Object.keys(accounts).map(id => ({ id, auth_index: id, provider: "codex", email: `${id}@example.invalid` })) });
      if (request.url?.endsWith("/api-call")) {
        const call = JSON.parse(raw);
        const account = accounts[call.auth_index as keyof typeof accounts];
        if (call.url.endsWith("/rate-limit-reset-credits")) return json({ status_code: 200, body: JSON.stringify({ credits: [] }) });
        const window = (seconds: number) => ({ used_percent: account.used, reset_at: Math.floor(now / 1000) + (account.used ? 3600 : 7200), limit_window_seconds: seconds });
        return json({ status_code: 200, body: JSON.stringify({ plan_type: account.plan, rate_limit: { primary_window: window(18000), secondary_window: window(604800) } }) });
      }
      response.writeHead(404).end();
    });
  });
  await new Promise<void>(resolve => hub.listen(18517, "127.0.0.1", resolve));
  try {
    await t3.project("Quota demonstration");
    await t3.open();
    await screen.getByRole("button", "Add project").waitFor({ state: "visible" });
    await app.open("/settings/providers");
    await screen.getByRole("button", "Add hub").tap();
    await screen.getByLabel("Hub URL").fill("http://127.0.0.1:18517");
    await screen.getByLabel("Management key").fill("synthetic-demo-key");
    await screen.getByLabel("Label (optional)").fill("Team hub");
    await screen.getByRole("button", "Add hub").tap();
    await app.open("/usage");
    await screen.getByRole("button", "Limits").tap();
    await screen.getByRole("button", /.*: 0% left/).first().waitFor({ state: "visible" });
    await app.screenshot("pooled-limits");
    await screen.getByRole("button", /.*: 0% left/).first().tap();
    await screen.getByText("ChatGPT Pro 200 Subscription").waitFor({ state: "visible" });
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {}))); });
    await app.screenshot("pro-reset-contribution");
    await expect.soft(screen.getByText("+95% of pool")).toBeVisible();
    await expect.soft(screen.getByText("5%").first()).toBeVisible();
  } finally {
    await new Promise<void>((resolve, reject) => hub.close(error => error ? reject(error) : resolve()));
  }
});
