import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4187;
const server = spawn('node', ['node_modules/vite/bin/vite.js', 'preview', '--port', String(PORT), '--strictPort'], { cwd: process.cwd(), stdio: 'pipe' });
const waitServer = () => new Promise((res, rej) => { const t=setTimeout(()=>rej('timeout'),30000); server.stdout.on('data',d=>{if(d.toString().includes('Local:')){clearTimeout(t);res();}}); server.stderr.on('data',d=>{if(d.toString().includes('Local:')){clearTimeout(t);res();}});});
const avgColor = (page) => page.evaluate(() => {
  const c = document.querySelector('canvas');
  const gl = c.getContext('webgl2') || c.getContext('webgl');
  const w=c.width,h=c.height; const fb=new Uint8Array(w*h*4);
  gl.readPixels(0,0,w,h,gl.RGBA,gl.UNSIGNED_BYTE,fb);
  let rs=0,gs=0,bs=0; const n=w*h;
  for (let i=0;i<fb.length;i+=4){rs+=fb[i];gs+=fb[i+1];bs+=fb[i+2];}
  return {r:rs/n,g:gs/n,b:bs/n, renderer: gl.getParameter(gl.RENDERER)};
});
try {
  await waitServer();
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('pageerror', (e) => console.log('PAGEERR', e.message));
  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1000);
  // go to plaza (more colorful than house)
  for (let i=0;i<24;i++){await page.keyboard.down('s');await page.waitForTimeout(40);} await page.keyboard.up('s'); await page.waitForTimeout(100);
  await page.keyboard.press('e'); await page.waitForTimeout(1200);
  // S0 (happy 10)
  await page.evaluate(()=>window.director.debugSetHappiness(10)); await page.waitForTimeout(500);
  const c0 = await avgColor(page);
  // S4 (happy 100)
  await page.evaluate(()=>window.director.debugSetHappiness(100)); await page.waitForTimeout(500);
  const c4 = await avgColor(page);
  console.log('S0 avg:', JSON.stringify(c0));
  console.log('S4 avg:', JSON.stringify(c4));
  console.log('renderer:', c0.renderer);
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
