import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4193;
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(1000);
  await page.keyboard.press('e'); await page.waitForTimeout(150); await page.keyboard.press('e'); await page.waitForTimeout(200);
  // set S4 + go to shop
  await page.evaluate(() => {
    window.director.debugSetHappiness(100);
    const g = window.game;
    g.scene.stop('HouseScene');
    g.scene.start('ShopScene', { spawn: 'default' });
  });
  await page.waitForTimeout(1000);
  // place player next to mimi
  await page.evaluate(() => {
    const shop = window.game.scene.getScene('ShopScene');
    shop.player.setPosition(120, 104); // just above mimi at (120,120)
  });
  await page.waitForTimeout(300);
  await page.keyboard.press('e'); // talk
  await page.waitForTimeout(900);
  // complete the typewriter
  await page.keyboard.press('e');
  await page.waitForTimeout(300);
  const dialogue = await page.evaluate(() => {
    const ui = window.game.scene.getScene('UIScene');
    return { bodyText: ui.bodyText?.text, nameText: ui.nameText?.text, stage: window.director.stage };
  });
  console.log('dialogue:', JSON.stringify(dialogue));
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
