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

// Read only the synthetic replay process for the thread this test just created.
function replayCredential(threadId: string) {
  for (const pid of fs.readdirSync('/proc').filter(x => /^\d+$/.test(x))) {
    try {
      const entries = fs.readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
      const env = Object.fromEntries(entries.map(x => { const i = x.indexOf('='); return [x.slice(0,i), x.slice(i+1)]; }));
      if (env.T3CODE_THREAD_ID === threadId && env.T3_ACP_MCP_AUTHORIZATION) return env;
    } catch {}
  }
  throw new Error('Synthetic replay process has no MCP credential');
}

test('Enlarging an agent-owned Browser panel preserves takeover, focus, typing and the stream', WEB,
async ({ t3, app, browser, screen }) => {
  let value = '';
  const server = http.createServer((req, res) => {
    const url = new URL(req.url!, 'http://fixture');
    if (url.pathname === '/value') { value = url.searchParams.get('text') ?? ''; res.end('ok'); return; }
    res.writeHead(200, {'content-type':'text/html'});
    res.end(`<!doctype html><title>Resize control check</title><style>body{margin:0;background:#f6f8fa;color:#18212b;font:20px system-ui}main{padding:24px}input{box-sizing:border-box;width:100%;padding:16px;font:24px system-ui}button{font:20px system-ui;padding:12px}output{display:block;margin-top:24px;white-space:pre-wrap}</style><main><h2>Browser resize control</h2><p>Search while resizing the Browser panel</p><button onclick="document.querySelector('input').focus()">Search</button><input aria-label="Search" placeholder="Type resize control" oninput="document.querySelector('output').textContent='Text received: '+this.value;fetch('/value?text='+encodeURIComponent(this.value))"><output>Text received: </output></main>`);
  });
  await new Promise<void>(resolve => server.listen(0,'127.0.0.1',resolve));
  try {
    await browser.setViewport({width:1100,height:800});
    await browser.emulateMedia({colorScheme:'light'});
    await browser.addInitScript(() => {
      const Original = window.WebSocket;
      (window as any).previewConnections = 0;
      window.WebSocket = class extends Original {
        constructor(url: string | URL, protocols?: string | string[]) {
          super(url, protocols);
          if (String(url).includes('/api/preview-stream/ws')) (window as any).previewConnections++;
        }
      };
    });
    const project = await t3.project('browser-demo');
    const thread = await t3.thread({project,title:'Browser resize control',messages:['Prepare browser check'],model:'question'});
    const env = replayCredential(thread.threadId);
    let session: string | null = null;
    let id = 0;
    const mcp = async (method: string, params: unknown) => {
      const r = await fetch(env.T3_ACP_MCP_ENDPOINT, {method:'POST',headers:{'Content-Type':'application/json',Accept:'application/json, text/event-stream',Authorization:env.T3_ACP_MCP_AUTHORIZATION,...(session ? {'mcp-session-id':session} : {})},body:JSON.stringify({jsonrpc:'2.0',id:++id,method,params})});
      session = r.headers.get('mcp-session-id') ?? session;
      const text = await r.text();
      if (!r.ok) throw new Error(`Synthetic replay MCP HTTP ${r.status}`);
      const payloads = text.startsWith('event:') || text.startsWith('data:') ? text.split('\n').filter(x=>x.startsWith('data:')).map(x=>JSON.parse(x.slice(5))) : [JSON.parse(text)];
      const result = payloads.find(x=>x.id === id);
      if (result?.error || result?.result?.isError) throw new Error(JSON.stringify(result));
      return result?.result;
    };
    await mcp('initialize',{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'resize-proof',version:'1'}});
    const address = server.address() as {port:number};
    await mcp('tools/call',{name:'preview_open',arguments:{url:`http://127.0.0.1:${address.port}`,open:true}});
    await mcp('tools/call',{name:'preview_resize',arguments:{mode:'fill'}});
    await t3.open(thread);
    await screen.getByRole('button','Toggle right panel').tap();
    await screen.getByRole('button','Take control').tap();
    await new Promise(resolve => setTimeout(resolve,1000));
    // The search box is the only form control after the Search button; click its
    // rendered position on the streamed page, rather than reaching into Chromium.
    const rect = await browser.evaluate(() => {
      const c = document.querySelector('canvas:has(~ textarea[aria-label="Browser page"])')!;
      const r = c.getBoundingClientRect();
      return {x:r.x,y:r.y,width:r.width,height:r.height,frameWidth:(c as HTMLCanvasElement).width,frameHeight:(c as HTMLCanvasElement).height};
    });
    await browser.mouse.move(rect.x + rect.width/2, rect.y + 238);
    await browser.mouse.down(); await browser.mouse.up();
    await new Promise(resolve => setTimeout(resolve,300));
    await browser.keyboard.type('resize ');
    await new Promise(resolve => setTimeout(resolve,1000));
    if (value !== 'resize ') throw new Error(`Search setup did not receive first word: ${JSON.stringify(value)}`);
    await app.screenshot('before-enlarging');
    const connections = await browser.evaluate(() => (window as any).previewConnections);
    await browser.setViewport({width:1800,height:1000});
    await new Promise(resolve => setTimeout(resolve,4000));
    const focusAfterResize = await browser.evaluate(() => document.activeElement?.getAttribute('aria-label') ?? document.activeElement?.tagName ?? '');
    await browser.keyboard.type('control');
    await new Promise(resolve => setTimeout(resolve,1000));
    await app.screenshot('after-enlarging-and-typing');
    const connectionsAfter = await browser.evaluate(() => (window as any).previewConnections);
    const frameAfter = await browser.evaluate(() => { const c = document.querySelector('canvas:has(~ textarea[aria-label="Browser page"])') as HTMLCanvasElement; return {width:c.width,height:c.height}; });
    console.log('Resize observations',JSON.stringify({before:rect,after:frameAfter,text:value,focus:focusAfterResize,connectionsBefore:connections,connectionsAfter}));
    expect(frameAfter.width > rect.frameWidth).toBe(true);
    expect({text:value,focus:focusAfterResize,streamConnections:connectionsAfter-connections}).toEqual({text:'resize control',focus:'Browser page',streamConnections:0});
    await expect(screen.getByText('You have control',{exact:true})).toBeVisible();
  } finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(()=>resolve())); }
});
