import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4221;
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);
  // enter plaza
  await page.keyboard.down('s');
  for (let i=0;i<15;i++){ await page.waitForTimeout(220); const a=await page.evaluate(()=>window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key)); if(a.includes('PlazaScene')) break; }
  await page.keyboard.up('s'); await page.waitForTimeout(800);
  // teleport player to center of plaza row 8 (y=136) col 14 (x=232)
  await page.evaluate(() => window.game.scene.getScene('PlazaScene').player.setPosition(232, 136));
  await page.waitForTimeout(300);
  const start = await page.evaluate(() => { const p=window.game.scene.getScene('PlazaScene').player; return {x:p.x,y:p.y}; });
  console.log('start at row8 center:', JSON.stringify(start));
  // walk left, sample position every 300ms
  await page.keyboard.down('a');
  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); const p=g.scene.getScene('PlazaScene').player; return {a, x:p?p.x:null, y:p?p.y:null}; });
    console.log('left step', i, JSON.stringify(s));
    if (s.a.includes('BakeryScene')) { console.log('ENTERED BAKERY'); break; }
    if (!s.a.includes('PlazaScene')) break;
  }
  await page.keyboard.up('a');
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
