import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4204;
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);
  // fully dismiss dialogue
  for (let i=0;i<4;i++){ await page.keyboard.press('e'); await page.waitForTimeout(150); }
  await page.click('canvas');
  await page.waitForTimeout(200);

  // check player internal keys
  const keys = await page.evaluate(() => {
    const p = window.game.scene.getScene('HouseScene').player;
    return {
      hasKLeft: !!p.kLeft,
      kLeftIsDown: p.kLeft && p.kLeft.isDown,
      kLeftPluginNull: p.kLeft && p.kLeft.plugin == null,
      wasdLen: p.wasdKeys ? p.wasdKeys.length : null,
      wasdDisDown: p.wasdKeys && p.wasdKeys[3] ? p.wasdKeys[3].isDown : null,
      moving: p.moving,
      frozen: p.frozen,
    };
  });
  console.log('player keys:', JSON.stringify(keys));

  // hold d, check player's internal D key
  await page.keyboard.down('d');
  await page.waitForTimeout(400);
  const during = await page.evaluate(() => {
    const p = window.game.scene.getScene('HouseScene').player;
    return {
      x: p.x, y: p.y,
      vx: p.body.velocity.x, vy: p.body.velocity.y,
      wasdDisDown: p.wasdKeys[3].isDown,
      kRightDown: p.kRight.isDown,
      moving: p.moving,
    };
  });
  console.log('DURING d-held:', JSON.stringify(during));
  await page.keyboard.up('d');
  await page.waitForTimeout(200);
  const after = await page.evaluate(() => ({x: window.game.scene.getScene('HouseScene').player.x, y: window.game.scene.getScene('HouseScene').player.y}));
  console.log('AFTER:', JSON.stringify(after));

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