import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// Synthetic 12-step replay: only the recording changes, never client/server logic.
test("A resumed feed commits its catch-up once and then streams live", WEB, async ({ t3, app, screen, browser }) => {
  const lines: unknown[] = [
    { type: "transcript_start", provider: "acpRegistry", protocol: "acp.ndjson-jsonrpc", version: 1, scenario: "echo_steps" },
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
  ];
  for (let i = 1; i <= 12; i++) {
    const push = (update: unknown, afterMs = 0) => lines.push({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update } } });
    push({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: `Step ${String(i).padStart(2, "0")} complete.\n\n` } }, 1500);
    push({ sessionUpdate: "tool_call", toolCallId: `echo-${i}`, kind: "execute", title: `echo step ${i}`, status: "in_progress", rawInput: { command: `echo step ${i}` } });
    push({ sessionUpdate: "tool_call_update", toolCallId: `echo-${i}`, status: "completed", content: [{ type: "content", content: { type: "text", text: `step ${i}` } }] }, 1500);
  }
  lines.push({ type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } });
  await writeFile(join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson"), lines.map(x => JSON.stringify(x)).join("\n") + "\n");
  await browser.addInitScript(() => {
    const Native = window.WebSocket;
    const state = (window as any).__catchup = { sockets: [], blocked: false, lag: false, syncing: false, intermediate: [], delivered: 0, cached: 2, sent: [], received: [] };
    const synthetic = new WeakSet();
    (window as any).WebSocket = class extends Native {
      threadRequests = new Set<string>();
      send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
        if (typeof data === "string") {
          const parsed = JSON.parse(data);
          for (const message of Array.isArray(parsed) ? parsed : [parsed]) {
            state.sent.push({ tag: message.tag, id: message.id, kind: message._tag });
            if (message.tag === "orchestration.subscribeThread") this.threadRequests.add(String(message.id));
          }
        }
        super.send(data);
      }
      constructor(...args: ConstructorParameters<typeof WebSocket>) {
        const url = new URL(String(args[0]), location.href);
        url.searchParams.delete("frameParts");
        super(url, args[1]);
        if (new URL(String(args[0]), location.href).pathname !== "/ws") return;
        state.sockets.push(this);
        this.addEventListener("open", () => { if (state.blocked) this.close(4000, "scenario offline"); });
        let chain = Promise.resolve();
        this.addEventListener("message", event => {
          if (synthetic.has(event)) return;
          if (!state.lag) return;
          event.stopImmediatePropagation();
          const data = JSON.parse(String(event.data));
          const messages = Array.isArray(data) ? data : [data];
          for (const message of messages) {
            // Reframe unchanged RPC stream values into small, ordered deliveries.
            state.received.push({ tag: message._tag, requestId: message.requestId, count: message.values?.length, kinds: message.values?.slice(0, 3).map((v: any) => v.kind) });
            const thread = message._tag === "Chunk" && this.threadRequests.has(String(message.requestId));
            const parts = thread ? message.values.map((v: any) => ({ ...message, values: [v] })) : [message];
            for (const part of parts) chain = chain.then(async () => {
              if (thread) await new Promise(r => setTimeout(r, 100));
              if (thread && part.values?.some((v: any) => v.kind === "synchronized")) state.syncing = false;
              const next = new MessageEvent("message", { data: JSON.stringify(part) });
              synthetic.add(next);
              this.dispatchEvent(next);
              if (thread) state.delivered++;
            });
          }
        });
      }
    };
    new MutationObserver(() => {
      if (!state.syncing) return;
      const steps = [...document.body.innerText.matchAll(/Step (\d+) complete/g)].map(m => Number(m[1]));
      const last = Math.max(0, ...steps);
      if (last > state.cached && !state.intermediate.includes(last)) state.intermediate.push(last);
    }).observe(document, { subtree: true, childList: true, characterData: true });
  });
  await t3.project("Catch-up demo");
  await t3.open();
  await screen.getByRole("textbox").fill("go");
  await screen.getByRole("textbox").press("Enter");
  await expect(screen.getByText("Step 02 complete.", { exact: false }).first()).toBeVisible();
  await app.screenshot("cached-feed");
  await browser.evaluate(() => {
    const s = (window as any).__catchup;
    s.cached = Math.max(...[...document.body.innerText.matchAll(/Step (\d+) complete/g)].map(m => Number(m[1])));
    s.blocked = true;
    s.sockets.forEach((ws: WebSocket) => ws.close(4000, "scenario offline"));
  });
  for (let i = 0; i < 3; i++) await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 15000)); return true; });
  await browser.evaluate(() => { const s = (window as any).__catchup; s.blocked = false; s.lag = true; s.syncing = true; });
  const retry = screen.getByRole("button", "Retry now");
  if (await retry.isVisible()) await retry.tap();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 6000)); return true; });
  await app.screenshot("catching-up");
  await expect(screen.getByText("Step 12 complete.", { exact: false }).first()).toBeVisible({ timeout: 60000 });
  await expect(screen.getByRole("button", "Stop generation")).toBeHidden({ timeout: 60000 });
  await app.screenshot("caught-up");
  const intermediate = await browser.evaluate(() => (window as any).__catchup.intermediate);
  await browser.evaluate(() => { (window as any).__catchup.lag = false; });
  await screen.getByRole("textbox").fill("live follow-up");
  await screen.getByRole("textbox").press("Enter");
  await expect(screen.getByRole("button", "Stop generation")).toBeVisible();
  await expect.poll(async () => browser.evaluate(() => { const text = document.body.innerText; return text.slice(text.lastIndexOf("live follow-up")).includes("Step 01 complete."); })).toBe(true);
  await app.screenshot("live-follow-up");
  expect(intermediate).toEqual([]);
});
