import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4213;
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));
async function walk(page, dir, ms){ await page.keyboard.down(dir); await page.waitForTimeout(ms); await page.keyboard.up(dir); await page.waitForTimeout(150); }
async function walkToScene(page, dir, wantScene, maxSteps=15){
  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;
}
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);

  // house -> plaza
  checks.house_to_plaza = await walkToScene(page, 's', 'PlazaScene');
  await page.waitForTimeout(600);
  // From plaza door_house (bottom center), walk UP to row 9, then LEFT to bakery door (5,9)
  await walk(page, 'w', 1800); // walk up
  checks.plaza_to_bakery = await walkToScene(page, 'a', 'BakeryScene');
  await page.waitForTimeout(500);
  // bakery -> plaza
  checks.bakery_to_plaza = await walkToScene(page, 's', 'PlazaScene');
  await page.waitForTimeout(500);
  // plaza: walk up then right to shop door (24,9)
  await walk(page, 'w', 1800);
  checks.plaza_to_shop = await walkToScene(page, 'd', 'ShopScene');
  await page.waitForTimeout(500);
  checks.shop_to_plaza = await walkToScene(page, 's', 'PlazaScene');
  await page.waitForTimeout(500);
  // plaza -> clinic (top center, door 14,1): walk up
  await walk(page, 'a', 800); // recenter
  checks.plaza_to_clinic = await walkToScene(page, 'w', 'ClinicScene');
  await page.waitForTimeout(500);
  checks.clinic_to_plaza = await walkToScene(page, 's', 'PlazaScene');
  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));
