import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4222;
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();}});});
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(1200);
  for (let i=0;i<4;i++){ await page.keyboard.press('e'); await page.waitForTimeout(120); }
  await page.click('canvas'); await page.waitForTimeout(300);
  await page.keyboard.down('s');
  for (let i=0;i<20;i++){
    await page.waitForTimeout(250);
    const s = await page.evaluate(() => { const g=window.game; const a=g.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key); let p=null; try{p={x:g.scene.getScene('HouseScene').player.x,y:g.scene.getScene('HouseScene').player.y};}catch(e){} return {a,p}; });
    console.log('s step', i, JSON.stringify(s));
    if (s.a.includes('PlazaScene')) { console.log('ENTERED PLAZA'); break; }
  }
  await page.keyboard.up('s');
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
