import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4211;
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 checks={};
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);

  // Walk down toward the door. Door at (88,112). Player starts ~ (96,64).
  // Just walk straight down — the door auto-trigger should fire when close.
  await page.keyboard.down('s');
  let escaped = false;
  for (let i=0;i<12;i++){
    await page.waitForTimeout(300);
    const st = await page.evaluate(() => {
      const g = window.game;
      const active = g.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key);
      return { active, hasPlaza: active.includes('PlazaScene'), hasHouse: active.includes('HouseScene') };
    });
    if (st.hasPlaza && !st.hasHouse) { escaped = true; break; }
  }
  await page.keyboard.up('s');
  checks.escaped_to_plaza = escaped;

  // Now from plaza, walk to each door and verify they auto-transition
  // plaza doors: door_house(bottom center 14,18), door_bakery(left 5,9), etc.
  // Wait for plaza to settle
  await page.waitForTimeout(800);
  const plazaActive = await page.evaluate(() => window.game.scene.scenes.filter(s=>s.scene.isActive()).some(s=>s.scene.key==='PlazaScene'));
  checks.in_plaza = plazaActive;

  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
console.log('CHECKS:', JSON.stringify(checks));
