import * as http from 'node:http';
import * as fs from 'node:fs/promises';
import { chromium } from 'playwright-core';
import { makeState, runPromise, rpcClient, environmentId } from './t3.ts';
import * as Effect from 'effect/Effect';
import { WS_METHODS, ProviderInstanceId } from '@t3tools/contracts';
import { T3_HOME } from '../e2e.config.ts';

const [origin,home,out]=process.argv.slice(2);
await fs.mkdir(out,{recursive:true});
const browser=await chromium.launch({headless:true,args:['--no-sandbox']});
const context=await browser.newContext({viewport:{width:1280,height:800},colorScheme:'light',recordVideo:{dir:out,size:{width:1280,height:800}}});
const page=await context.newPage();
const screen={getByRole:(role:string,name:string)=>{const l=page.getByRole(role as any,{name,exact:true});return {tap:()=>l.click(),waitFor:(opts:any)=>l.waitFor(opts)};}};
const app={baseUrl:origin,screenshot:async(label:string)=>{let previous=await page.screenshot();for(let i=0;i<10;i++){await new Promise(r=>setTimeout(r,500));const current=await page.screenshot();if(current.equals(previous)){await fs.writeFile(out+'/'+label+'.png',current);return;}previous=current;}throw new Error('Screenshot did not stabilize');}};
const state=makeState(home);
const t3={...state.state,open:async(thread:any)=>{const credential=await fs.readFile(home+'/browser-dev-token','utf8');const auth=await context.request.post(origin+'/api/auth/browser-session',{data:{credential}});if(!auth.ok())throw new Error('Login failed');const envId=await runPromise(environmentId(origin));await page.goto(origin+'/'+envId+'/'+thread.threadId);}};
try {
  const project = await t3.project('literal-preview');
  await runPromise(Effect.scoped(Effect.gen(function*(){
    const client=yield* rpcClient(home,origin);
    yield* client[WS_METHODS.serverRefreshProviders]({instanceId:ProviderInstanceId.make('devReplay'),cwd:project,fresh:true,refreshModels:true});
  })));
  try {await t3.thread({project,title:'Warm replay catalog',model:'multi-turn',messages:['Start']});}catch(error){if(!String(error).includes('Advertised models: default'))throw error;await t3.thread({project,title:'Warm replay catalog',model:'default',messages:['Start']});}
  const launched = await runPromise(state.cli(['thread','start',project,'Keep streaming','--provider','devReplay','--model','bench-stream','--title','Literal preview wait','--json']));
  const thread = JSON.parse(launched.stdout);
  await t3.open(thread);
  await screen.getByRole('button','Stop generation').waitFor({state:'visible'});
  // Read the environment of only this fixture's replay process. No credentials enter artifacts.
  let session: {endpoint?:string;authorization?:string} = {};
  for (const entry of await fs.readdir('/proc')) {
    if (!/^\d+$/.test(entry)) continue;
    try {
      if (await fs.readlink(`/proc/${entry}/cwd`) !== project) continue;
      const command = await fs.readFile(`/proc/${entry}/cmdline`, 'utf8');
      if (!command.includes('dev-replay-agent.ts')) continue;
      const env = Object.fromEntries((await fs.readFile(`/proc/${entry}/environ`,'utf8')).split('\0').filter(Boolean).map(item=>{const i=item.indexOf('=');return [item.slice(0,i),item.slice(i+1)];}));
      if(env.T3CODE_THREAD_ID !== thread.threadId) continue;
      session={endpoint:env.T3_ACP_MCP_ENDPOINT,authorization:env.T3_ACP_MCP_AUTHORIZATION};
      if(session.authorization) break;
    } catch {}
  }
  if (!session.authorization || !session.endpoint) throw new Error('Own replay process has no preview MCP session');
  let sessionId = '';
  let id=0;
  async function rpc(method:string,params?:object) {
    const response=await fetch(session.endpoint,{method:'POST',headers:{'content-type':'application/json',accept:'application/json, text/event-stream',authorization:session.authorization,...(sessionId?{'mcp-session-id':sessionId}:{})},body:JSON.stringify({jsonrpc:'2.0',...(method.startsWith('notifications/')?{}:{id:++id}),method,params})});
    sessionId=response.headers.get('mcp-session-id')??sessionId;
    const text=await response.text();
    if(!response.ok) throw new Error(`MCP ${response.status}: ${text}`);
    if(!text) return {};
    const data=text.startsWith('event:')||text.startsWith('data:')?text.split('\n').filter(x=>x.startsWith('data: ')).map(x=>JSON.parse(x.slice(6))).find(x=>x.id===id):JSON.parse(text);
    return data.error?{isError:true,content:[{type:'text',text:JSON.stringify(data.error)}]}:data.result??data;
  }
  await rpc('initialize',{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'literal-wait-proof',version:'1'}});
  await rpc('notifications/initialized');
  const call=(name:string,args:object)=>rpc('tools/call',{name,arguments:args});
  const lines:string[]=[];
  const fixture=http.createServer((req,res)=>{res.setHeader('content-type','text/html');res.end(req.url==='/report'?`<meta charset="utf-8"><body style="font:40px monospace;background:#fff;color:#111;padding:24px"><h2>Literal preview wait — runtime results</h2><pre style="white-space:pre-wrap">${lines.join('\n').replaceAll('&','&amp;').replaceAll('<','&lt;')}</pre></body>`:`<div style="white-space:pre">${req.url==='/ready-space.html'?'READY ':'READY'}</div>`);});
  await new Promise<void>(resolve=>fixture.listen(0,'127.0.0.1',resolve));
  const address=fixture.address() as {port:number};
  const url=`http://127.0.0.1:${address.port}`;
  const value=(r:any)=>r.structuredContent?.value??JSON.parse(r.content.find((x:any)=>x.type==='text').text).value;
  const summarize=(r:any)=>r.isError?'ERROR: '+r.content?.map((x:any)=>x.text??'').join(' '):'SUCCESS';
  try {
    await screen.getByRole('button','Toggle right panel').tap();
    await screen.getByRole('button','Browser B').tap();
    const opened=await call('preview_open',{url:url+'/ready.html'});
    if(opened.isError) throw new Error(JSON.stringify(opened));
    const noSpaceText=await call('preview_evaluate',{expression:'JSON.stringify(document.body.innerText)'});
    lines.push('Page: ready.html','Rendered text: '+value(noSpaceText));
    const control=await call('preview_wait_for',{text:'READY',timeoutMs:60});
    lines.push('wait text="READY": '+summarize(control));
    if(control.isError) throw new Error('Control wait failed: '+JSON.stringify(control));
    const missing=await call('preview_wait_for',{text:'READY ',timeoutMs:60});
    lines.push('wait text="READY ": '+summarize(missing),'Expected: timeout (trailing space absent)','');
    await call('preview_navigate',{url:url+'/ready-space.html'});
    const spaceText=await call('preview_evaluate',{expression:'JSON.stringify(document.body.innerText)'});
    lines.push('Page: ready-space.html','Rendered text: '+value(spaceText));
    const present=await call('preview_wait_for',{text:'READY ',timeoutMs:60});
    lines.push('wait text="READY ": '+summarize(present),'Expected: success (trailing space present)');
    for(const text of ['', '   ']) { const invalid=await call('preview_wait_for',{text,timeoutMs:60}); lines.push('wait text='+JSON.stringify(text)+': '+(invalid.isError?'INVALID (rejected)':'UNEXPECTED SUCCESS')); }
    await call('preview_navigate',{url:url+'/report'});
    await page.getByRole('button',{name:'Close floating preview',exact:true}).click({force:true});
    await page.getByRole('button',{name:`127.0.0.1:${address.port}`,exact:true}).click();
    await call('preview_resize',{width:520,height:600});
    const snapshot=await call('preview_snapshot',{includeImage:true});
    const pixels=snapshot.content?.find((x:any)=>x.type==='image');if(pixels) await fs.writeFile(out+'/browser-runtime-results.png',Buffer.from(pixels.data,'base64'));
    await page.getByRole('button',{name:'Stop generation',exact:true}).click();
    await page.getByRole('button',{name:'Stop generation',exact:true}).waitFor({state:'hidden'});
    await app.screenshot('literal-wait-runtime-results');
    const result={missingSpaceTimedOut:missing.isError===true && /timed out after 60ms|Waited 60ms/.test(JSON.stringify(missing)),presentSpaceSucceeded:present.isError!==true,lines};
    await fs.writeFile(out+'/result.json',JSON.stringify(result,null,2));console.log(JSON.stringify(result));
  } finally {
    await call('t3_preview_list',{}).then(async result=>{const content=result.structuredContent;for(const tab of content?.tabs??[]) await call('t3_preview_close',{tabId:tab.tabId});}).catch(()=>{});
    await new Promise<void>(resolve=>fixture.close(()=>resolve()));
  }
} finally {await runPromise(state.cleanup).catch(()=>{});await context.close();await browser.close();}
