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

const PROBE = String.raw`import { writeFileSync } from 'node:fs';
import { once } from 'node:events';
const file = n => new URL(n, import.meta.url);
let phase = 'ready', input = '', first = '', timer;
process.stdin.setRawMode(true);
process.stdin.on('data', async chunk => {
  input += chunk.toString();
  const reply = input.match(/\x1b\[\d+;\d+R/);
  if (reply) {
    input = '';
    if (phase === 'first') {
      first = JSON.stringify(reply[0]); phase = 'owned';
      writeFileSync(file('first'), first);
      process.stdout.write('\r\nFirst reply received. Viewer A owns query replies.\r\nPress s from viewer B after stalling A.\r\n');
    } else if (phase === 'second') {
      clearTimeout(timer); phase = 'done';
      const result = 'PASS: second cursor-position reply received';
      writeFileSync(file('result'), result);
      process.stdout.write('\r\n' + result + '\r\nReply: ' + JSON.stringify(reply[0]) + '\r\n');
    }
    return;
  }
  if (phase === 'ready' && input.includes('f')) {
    input = ''; phase = 'first'; process.stdout.write('\x1b[6n');
  } else if (phase === 'owned' && input.includes('s')) {
    input = ''; phase = 'burst';
    for (let i = 0; i < 288; i++) {
      if (!process.stdout.write('x'.repeat(32766) + '\r\n')) await once(process.stdout, 'drain');
    }
    process.stdout.write('\x1b[2J\x1b[HShared terminal query probe\r\nFirst reply received from viewer A.\r\nViewer A stalled; WebSocket remains open.\r\nViewer B received 288 x 32 KiB = 9 MiB burst.\r\nWaiting for cursor position...\r\n');
    phase = 'second'; process.stdout.write('\x1b[6n');
    timer = setTimeout(() => {
      phase = 'done'; const result = 'TIMEOUT: no reply to second query';
      writeFileSync(file('result'), result);
      process.stdout.write('\r\n' + result + '\r\nNo cursor-position reply received.\r\n');
    }, 4000);
  }
});
process.stdout.write('\x1b[2J\x1b[HShared terminal query probe\r\nPress f to establish viewer A as query-reply owner.\r\n');
writeFileSync(file('ready'), 'ready');
`;

test('A live viewer answers terminal queries after the previous owner stalls', WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project('query-demo', {'query-probe.mjs': PROBE});
  const thread = await t3.thread({project, title: 'Shared terminal query', messages: ['hello']});
  const read = (name: string) => readFile(`${project}/${name}`, 'utf8').catch(() => '');
  await browser.addInitScript(() => {
    const state = {stall: false, dropped: 0, replies: [] as string[], ids: [] as string[]};
    (window as any).queryProof = state;
    const Native = WebSocket;
    class GatedSocket extends Native {
      constructor(url: string | URL, protocols?: string | string[]) {
        super(url, protocols);
        this.addEventListener('message', event => {
          let frames;
          try { frames = [JSON.parse(String(event.data))].flat(); } catch { return; }
          if (window === window.top && state.stall && frames.some(f => f._tag === 'Chunk' && state.ids.includes(String(f.requestId)))) {
            state.dropped++; event.stopImmediatePropagation();
          }
        });
      }
      send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
        if (typeof data === 'string') {
          try {
            for (const f of [JSON.parse(data)].flat()) {
              if (f.tag === 'terminal.attach') state.ids.push(String(f.id));
              if (f.tag === 'terminal.write' && f.payload?.reply) state.replies.push(f.payload.data);
            }
          } catch {}
        }
        super.send(data);
      }
    }
    window.WebSocket = GatedSocket;
  });
  await browser.emulateMedia({colorScheme:'dark', reducedMotion:'reduce'});
  await t3.open(thread);
  await screen.getByRole('button', 'Toggle terminal drawer').tap();
  const terminal = screen.getByLabel('Terminal input');
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type(`echo ready > '${project}/shell-ready'`);
    await browser.keyboard.press('Enter');
    return read('shell-ready');
  }, {timeout:30000}).toBe('ready\n');
  await terminal.focus();
  await browser.keyboard.type(`node query-probe.mjs`);
  await browser.keyboard.press('Enter');
  await expect.poll(() => read('ready')).toBe('ready');
  await browser.keyboard.type('f');
  await expect.poll(() => read('first')).not.toBe('');
  await app.screenshot('viewer-a-first-reply');
  await browser.evaluate(() => {
    (window as any).queryProof.stall = true;
    const frame = document.createElement('iframe');
    frame.id = 'live-viewer'; frame.src = location.href;
    frame.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;z-index:2147483647;border:0;background:#111';
    document.body.append(frame);
    return null;
  });
  const live = browser.frameLocator('#live-viewer');
  const liveTerminal = live.getByLabel('Terminal input');
  await live.getByRole('button', 'Toggle terminal drawer').waitFor();
  try { await liveTerminal.waitFor({timeout:3000}); } catch { await live.getByRole('button', 'Toggle terminal drawer').tap(); }
  await liveTerminal.waitFor();
  await liveTerminal.focus();
  await browser.keyboard.type('s');
  await expect.poll(() => read('result'), {timeout:15000}).not.toBe('');
  // The final probe output must have reached the live renderer before capture.
  await expect.poll(() => browser.evaluate(() => {
    const frame = document.querySelector<HTMLIFrameElement>('#live-viewer');
    return (frame?.contentWindow as any)?.queryProof.replies.length ?? 0;
  })).toBeGreaterThan(0);
  await app.screenshot('second-query-result');
  const diagnostic = await browser.evaluate(() => ({dropped:(window as any).queryProof.dropped, replies:((document.querySelector<HTMLIFrameElement>('#live-viewer')?.contentWindow as any)?.queryProof.replies ?? [])}));
  console.log('Query diagnostic', JSON.stringify(diagnostic));
  expect(await read('result')).toBe('PASS: second cursor-position reply received');
});
