/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Clear and resize remain responsive while a real terminal keeps printing", WEB, async ({ t3, app, browser, screen }) => {
  await browser.addInitScript(() => {
    const w = window as any;
    const probe = w.terminalProof = { socket: null, pending: new Map(), next: 800000, output: 0, cleared: 0, lines: [], summary: "Preparing real terminal" };
    const seen = new Set<string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") { try { if ([JSON.parse(data)].flat().some(m => m._tag === "Request")) probe.socket = this; } catch {} }
      return send.call(this, data);
    };
    const add = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(type, listener, options) {
      if (type === "message") {
        const wrapped = function(this: WebSocket, event: MessageEvent) {
          const visit = (v: any) => {
            if (!v || typeof v !== "object") return;
            if (v._tag === "Exit" && probe.pending.has(String(v.requestId))) {
              const done = probe.pending.get(String(v.requestId)); probe.pending.delete(String(v.requestId)); done(v.exit);
            }
            if (v.type === "output" || v.type === "cleared") {
              const key = `${v.terminalId}:${v.sequence}:${v.type}`;
              if (v.sequence === undefined || !seen.has(key)) { if (v.type === "output") probe.output++; else probe.cleared++; seen.add(key); }
            }
            for (const value of Object.values(v)) if (typeof value === "object") visit(value);
          };
          try { visit(JSON.parse(event.data)); } catch {}
          if (typeof listener === "function") listener.call(this, event); else listener?.handleEvent(event);
        };
        return add.call(this, type, wrapped as EventListener, options);
      }
      return add.call(this, type, listener, options);
    } as typeof WebSocket.prototype.addEventListener;
    probe.call = (tag: string, payload: any) => new Promise(resolve => {
      const id = String(++probe.next); probe.pending.set(id, resolve);
      probe.socket.send(JSON.stringify({ _tag: "Request", id, tag, payload, headers: [] }));
    });
    setInterval(() => {
      if (!document.body) return;
      let box = document.getElementById("terminal-proof-status");
      if (!box) { box = document.createElement("pre"); box.id = "terminal-proof-status"; document.body.append(box); Object.assign(box.style, { position: "fixed", top: "70px", right: "20px", width: "530px", padding: "18px", zIndex: "99999", background: "#101820", color: "#fff", border: "2px solid #6b9", font: "15px/1.5 monospace", whiteSpace: "pre-wrap" }); }
      box.textContent = "REAL TERMINAL RPC OBSERVER\n" + probe.summary + "\nOutput chunks: " + probe.output + " | cleared events: " + probe.cleared + "\n" + probe.lines.slice(-12).join("\n");
    }, 250);
  });
  const project = await t3.project("terminal-proof");
  const thread = await t3.thread({ project, title: "Clear while printing", messages: ["go"] });
  await t3.open(thread);
  // Open through the real RPC before showing the drawer, with a synthetic prompt.
  await browser.evaluate(async ({threadId, cwd}) => {
    const p = (window as any).terminalProof;
    for (let i = 0; !p.socket && i < 300; i++) await new Promise(r => setTimeout(r, 100));
    await p.call("terminal.open", {threadId, terminalId: "default", cwd, cols: 80, rows: 24, env: {PS1: "$ ", PROMPT_COMMAND: ""}});
    await p.call("terminal.write", {threadId, terminalId: "default", data: "export PS1='$ '; printf '\\033[2J\\033[H'; while :; do printf 'tick\\n'; sleep 0.01; done\r"});
  }, {threadId: thread.threadId, cwd: project});
  await screen.getByRole("button", "Toggle terminal drawer", {exact: true}).tap();
  await browser.evaluate((threadId) => {
    (window as any).terminalProof.result = null;
    void (async () => {
    const p = (window as any).terminalProof;
    const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
    const payload = {threadId, terminalId: "default"};
    await p.call("terminal.resize", {...payload, cols: 80, rows: 24});
    await sleep(1500);
    let ok = true;
    for (let round = 1; round <= 20; round++) {
      p.summary = `Round ${round}/20: clear, resize 500 ms later; output continues`;
      const start = performance.now();
      let clearMs: number | null = null, resizeMs: number | null = null;
      const clear = p.call("terminal.clear", payload).then((exit: any) => { clearMs = Math.round(performance.now()-start); if (exit._tag !== "Success") throw Error(JSON.stringify(exit)); });
      await sleep(500);
      const resizeStart = performance.now();
      const resize = p.call("terminal.resize", {...payload, cols: 80, rows: 24}).then(() => { resizeMs = Math.round(performance.now()-resizeStart); });
      const completed = await Promise.race([Promise.all([clear, resize]).then(() => true), sleep(20000).then(() => false)]);
      p.lines.push(`Round ${round}: clear ${clearMs === null ? "PENDING >20s" : clearMs+"ms"}; resize ${resizeMs === null ? "PENDING" : resizeMs+"ms"}`);
      if (!completed) {
        ok = false;
        const chunks = p.output;
        p.summary = "STUCK: holding continuous output for 30 more seconds";
        await sleep(30000);
        p.lines.push(`30s hold: +${p.output-chunks} chunks; clear ${clearMs === null ? "still PENDING" : clearMs+"ms"}`);
        p.summary = "FAIL: clear and resize blocked while output keeps streaming";
        break;
      }
      await sleep(200);
    }
    if (ok) p.summary = "PASS: all 20 clears and following resizes returned while printing";
    await sleep(600);
    (window as any).terminalProof.result = ok;
    })();
    return null;
  }, thread.threadId);
  let result: boolean | null = null;
  for (let i = 0; i < 120 && result === null; i++) {
    result = await browser.evaluate(async () => {
      await new Promise(r => setTimeout(r, 1000));
      return (window as any).terminalProof.result;
    });
  }
  await app.screenshot("clear-while-printing");
  await browser.evaluate(async (threadId) => {
    const p = (window as any).terminalProof;
    await p.call("terminal.write", {threadId, terminalId: "default", data: "\u0003"});
    await new Promise(r => setTimeout(r, 1000));
  }, thread.threadId);
  expect(result).toBe(true);
});
