import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4203;
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 } });
  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1200);
  await page.keyboard.press('e'); await page.waitForTimeout(200); await page.keyboard.press('e'); await page.waitForTimeout(200);

  // Inspect wasd key objects in detail
  const wasdDetail = await page.evaluate(() => {
    const h = window.game.scene.getScene('HouseScene');
    const d = h.wasd.D;
    return {
      type: typeof d,
      hasKeyCode: 'keyCode' in d,
      keyCode: d.keyCode,
      isDown: d.isDown,
      sceneInputEnabled: d.scene && d.scene.input ? d.scene.input.enabled : 'no scene ref',
      // check which scene the key belongs to
      sceneKey: d.scene ? d.scene.sys.config.key : null,
    };
  });
  console.log('wasd.D detail:', JSON.stringify(wasdDetail, null, 2));

  // Also test: create a fresh key and see if it tracks
  const freshTest = await page.evaluate(() => {
    const h = window.game.scene.getScene('HouseScene');
    const k = h.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
    h.__testD = k;
    return { keyCode: k.keyCode };
  });
  await page.keyboard.down('d');
  await page.waitForTimeout(200);
  const freshDown = await page.evaluate(() => ({ testD: window.game.scene.getScene('HouseScene').__testD.isDown, wasdD: window.game.scene.getScene('HouseScene').wasd.D.isDown }));
  console.log('fresh key d held:', JSON.stringify(freshDown));
  await page.keyboard.up('d');

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