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

test("Pooled Claude quota stays stable when only reset order changes", WEB, async ({ t3, app, screen, browser }) => {
  let reversed = false;
  let changed = false;
  const used = [94, 94.3, 97.9, 99.8];
  const hub = createServer(async (request, response) => {
    const path = new URL(request.url!, "http://localhost").pathname;
    let result: unknown;
    if (path.endsWith("/auth-files/models")) {
      response.writeHead(404).end("{}"); return;
    }
    if (path.endsWith("/auth-files")) {
      result = { files: used.map((_, i) => ({ id: `account-${i + 1}.json`, auth_index: String(i), provider: "claude", email: `account${i + 1}@example.invalid` })) };
    } else {
      let body = "";
      for await (const part of request) body += part;
      const i = Number(JSON.parse(body).auth_index);
      result = { status_code: 200, body: JSON.stringify({ five_hour: { utilization: used[i] + (changed ? 0.1 : 0), resets_at: new Date(Date.now() + (reversed ? 4 - i : i + 1) * 3600000).toISOString() } }) };
    }
    response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(result));
  });
  await new Promise<void>((resolve) => hub.listen(0, "127.0.0.1", resolve));
  try {
    const address = hub.address() as { port: number };
    const project = await t3.project("Quota demo");
    await t3.thread({ project, title: "Usage proof", messages: ["Ready"] });
    await t3.open("/settings/providers");
    await screen.getByRole("button", "Add hub", { exact: true }).tap();
    await screen.getByLabel("Hub URL", { exact: true }).fill(`http://127.0.0.1:${address.port}`);
    await screen.getByLabel("Management key", { exact: true }).fill("synthetic-proof-key");
    await screen.getByLabel("Label (optional)", { exact: true }).fill("Synthetic quota hub");
    await screen.getByRole("button", "Add hub", { exact: true }).tap();
    await screen.getByText("Synthetic quota hub", { exact: true }).waitFor();
    await t3.open("/usage");
    await screen.getByRole("button", "Limits", { exact: true }).tap();
    const headline = browser.locator("section .text-3xl");
    await headline.waitFor();
    await screen.getByRole("button", "Refresh limits", { exact: true }).waitFor({ state: "visible" });
    const read = () => browser.evaluate<string>('Array.from(document.querySelectorAll("section")).find(s => s.querySelector("h2")?.textContent?.trim() === "Claude")?.querySelector(".text-3xl")?.textContent ?? ""');
    const refresh = async () => {
      const button = screen.getByRole("button", "Refresh limits", { exact: true });
      await button.tap();
      await expect(button).toBeEnabled();
    };
    await refresh();
    const ascending = await read();
    await app.screenshot("ascending-resets");
    reversed = true;
    await refresh();
    const descending = await read();
    await app.screenshot("descending-resets");
    reversed = false;
    await refresh();
    const ascendingAgain = await read();
    await app.screenshot("ascending-again");
    changed = true;
    await refresh();
    const differentMean = await read();
    await app.screenshot("genuinely-higher-usage");
    expect({ descending, ascendingAgain }).toEqual({ descending: ascending, ascendingAgain: ascending });
    expect(differentMean).toBe("3%");
    expect(ascending).toBe("4%");
  } finally {
    await new Promise<void>((resolve, reject) => hub.close(error => error ? reject(error) : resolve()));
  }
});
