import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4218;
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(150); }
  await page.click('canvas'); await page.waitForTimeout(300);
  // teleport directly to plaza to skip the house
  await page.evaluate(() => {
    const g = window.game;
    g.scene.stop('HouseScene');
    g.scene.start('PlazaScene', { spawn: 'default' });
  });
  await page.waitForTimeout(1200);
  await page.click('canvas'); await page.waitForTimeout(200);

  const before = await page.evaluate(() => { const p=window.game.scene.getScene('PlazaScene').player; return {x:p.x,y:p.y,active:window.game.scene.getScene('PlazaScene').scene.isActive(),moving:p.moving}; });
  console.log('before (plaza default spawn):', JSON.stringify(before));

  await page.keyboard.down('w'); await page.waitForTimeout(600);
  const during = await page.evaluate(() => { const p=window.game.scene.getScene('PlazaScene').player; return {x:p.x,y:p.y,vy:p.body.velocity.y}; });
  console.log('w held 600ms:', JSON.stringify(during));
  await page.keyboard.up('w');
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
