import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4205;
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 pos = () => page.evaluate(() => { const p=window.game.scene.getScene('HouseScene').player; return {x:p.x,y:p.y}; });
let page;
try {
  await waitServer();
  const browser = await chromium.launch();
  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(200);

  for (const [key, label] of [['d','right'],['a','left'],['s','down'],['w','up'],['ArrowRight','arrowR'],['ArrowLeft','arrowL'],['ArrowUp','arrowU'],['ArrowDown','arrowD']]) {
    const b = await pos();
    await page.keyboard.down(key); await page.waitForTimeout(350); await page.keyboard.up(key); await page.waitForTimeout(80);
    const a = await pos();
    const moved = Math.abs(a.x-b.x) > 3 || Math.abs(a.y-b.y) > 3;
    checks[label] = moved;
    console.log(`${label}: (${b.x.toFixed(0)},${b.y.toFixed(0)}) -> (${a.x.toFixed(0)},${a.y.toFixed(0)}) moved=${moved}`);
  }
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
console.log('CHECKS:', JSON.stringify(checks));
