import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const counts = [1150, 1250, 9950, 9950000];
const transcript = counts.flatMap((used) => [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: {
    sessionId: "<session-id>", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `Reporting usage_update used=${used} size=${used < 100000 ? 100000 : 100000000}` } }
  } } },
  { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: {
    sessionId: "<session-id>", update: { sessionUpdate: "usage_update", used, size: used < 100000 ? 100000 : 100000000 }
  } } },
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
]).map((entry) => JSON.stringify(entry)).join("\n");

test("Exact half-step context counts round up consistently", WEB, async ({ t3, app, screen, browser }) => {
  const replayAgent = await NodeFSP.readFile(new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url), "utf8");
  const project = await t3.project("context-rounding", {
    "replay/dev-replay-agent.ts": replayAgent,
    "replay/dev-replay/showcase_transcript.ndjson": transcript,
  });
  const instanceId = ProviderInstanceId.make("context-replay");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId, instance: {
        driver: ProviderDriverKind.make("acpRegistry"), displayName: "Context usage replay", enabled: true,
        config: { source: "local", commandPath: process.execPath, commandArgs: [NodePath.join(project, "replay/dev-replay-agent.ts")] },
      },
    } });
  }).pipe(Effect.scoped));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Report USED=1150", "--title", "Exact half-step context counts", "--provider", instanceId, "--model", "default", "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open({ threadId });
  await screen.getByText("Reporting usage_update used=1150 size=100000", { exact: true }).waitFor();
  await browser.evaluate(() => {
    const card = document.querySelector("[data-thread-details-card]");
    if (!card) throw new Error("Thread details panel missing");
    card.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: 1000, clientY: 400 }));
  });
  await screen.getByRole("menuitemcheckbox", "Context window", { exact: true }).tap();
  await screen.getByRole("textbox").press("Escape");
  const observed: string[] = [];
  for (const used of counts) {
    if (used !== 1150) {
      await runPromise(cli(["thread", "send", threadId, `Report USED=${used}`, "--wait", "--json"]));
      await screen.getByText(`Reporting usage_update used=${used} size=${used < 100000 ? 100000 : 100000000}`, { exact: true }).waitFor();
    }
    const row = browser.locator('section[aria-label="Context window"]');
    await row.waitFor();
    await app.screenshot(`context-${used}`);
    observed.push((await row.textContent()) ?? "");
  }
  expect(observed).toEqual([
    expect.stringContaining("1.2k / 100k"),
    expect.stringContaining("1.3k / 100k"),
    expect.stringContaining("10k / 100k"),
    expect.stringContaining("10m / 100m"),
  ]);
});
