import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4201;
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('console', (msg) => { if (msg.type()==='error'||msg.type()==='warn') console.log('CONSOLE', msg.type(), msg.text()); });
  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);

  // check keyboard setup
  const setup = await page.evaluate(() => {
    const house = window.game.scene.getScene('HouseScene');
    return {
      kbExists: !!house.input.keyboard,
      cursorsExists: !!house.cursors,
      wasdExists: !!house.wasd,
      wasdKeys: house.wasd ? Object.keys(house.wasd) : null,
      wasdA: house.wasd && house.wasd.A ? { isDown: house.wasd.A.isDown, keyCode: house.wasd.A.keyCode } : null,
      playerExists: !!house.player,
      playerPos: house.player ? {x:house.player.x, y:house.player.y} : null,
      dialogueActive: window.game.scene.getScene('UIScene').active,
    };
  });
  console.log('SETUP:', JSON.stringify(setup, null, 2));

  // dismiss dialogue if active
  if (setup.dialogueActive) {
    await page.keyboard.press('e'); await page.waitForTimeout(200);
    await page.keyboard.press('e'); await page.waitForTimeout(200);
  }

  const before = await page.evaluate(() => ({x: window.game.scene.getScene('HouseScene').player.x, y: window.game.scene.getScene('HouseScene').player.y, v: window.game.scene.getScene('HouseScene').player.body.velocity}));

  // press and hold 'd' for 500ms
  await page.keyboard.down('d');
  await page.waitForTimeout(500);
  const during = await page.evaluate(() => ({
    x: window.game.scene.getScene('HouseScene').player.x,
    y: window.game.scene.getScene('HouseScene').player.y,
    v: {x: window.game.scene.getScene('HouseScene').player.body.velocity.x, y: window.game.scene.getScene('HouseScene').player.body.velocity.y},
    wasdD_isDown: window.game.scene.getScene('HouseScene').wasd.D.isDown,
    cursorsRight: window.game.scene.getScene('HouseScene').cursors.right.isDown,
  }));
  await page.keyboard.up('d');
  await page.waitForTimeout(100);
  const after = await page.evaluate(() => ({x: window.game.scene.getScene('HouseScene').player.x, y: window.game.scene.getScene('HouseScene').player.y}));

  console.log('BEFORE:', JSON.stringify(before));
  console.log('DURING (d held):', JSON.stringify(during));
  console.log('AFTER:', JSON.stringify(after));

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