import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4212;
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={};
const getActive = (page) => page.evaluate(() => window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key));
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);

  // helper: walk in a direction until scene changes or timeout
  async function walkToScene(dir, wantScene, maxSteps=12) {
    await page.keyboard.down(dir);
    for (let i=0;i<maxSteps;i++){
      await page.waitForTimeout(300);
      const a = await getActive(page);
      if (a.includes(wantScene)) { await page.keyboard.up(dir); return true; }
    }
    await page.keyboard.up(dir);
    return false;
  }

  // house -> plaza (walk down)
  checks.house_to_plaza = await walkToScene('s', 'PlazaScene');
  await page.waitForTimeout(500);

  // plaza -> bakery (door at left tile 5,9 = walk left). Player spawns near door_house (bottom center).
  // First walk up, then left to bakery door
  checks.plaza_to_bakery = await walkToScene('a', 'BakeryScene');
  await page.waitForTimeout(500);

  // bakery -> plaza (door at bottom center 7,9, walk down)
  checks.bakery_to_plaza = await walkToScene('s', 'PlazaScene');
  await page.waitForTimeout(500);

  // plaza -> shop (door at right tile 24,9, walk right)
  checks.plaza_to_shop = await walkToScene('d', 'ShopScene');
  await page.waitForTimeout(500);

  // shop -> plaza
  checks.shop_to_plaza = await walkToScene('s', 'PlazaScene');
  await page.waitForTimeout(500);

  // plaza -> house (door_house bottom center 14,18, walk down)
  checks.plaza_to_house = await walkToScene('s', 'HouseScene');
  await page.waitForTimeout(500);

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