import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4197;
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={};
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 day 6, go to plaza
  await page.evaluate(() => {
    window.director.debugSetDay(6);
    const g = window.game;
    g.scene.stop('HouseScene');
    g.scene.start('PlazaScene', { spawn: 'default' });
  });
  await page.waitForTimeout(1000);
  // place player at smile spot (tile 15,10 = 248, 168) and trigger T14
  await page.evaluate(() => {
    const plaza = window.game.scene.getScene('PlazaScene');
    plaza.player.setPosition(248, 168);
  });
  await page.waitForTimeout(300);
  await page.keyboard.press('e'); // trigger smile task
  await page.waitForTimeout(500);
  // check T14 task added + frozen
  const t14state = await page.evaluate(() => ({
    taskAdded: window.director.tasksDone.has('T14'),
    silenceFactor: null,
  }));
  checks.t14_started = t14state.taskAdded;
  // wait 3s and check camera zoom increased
  const z0 = await page.evaluate(() => window.game.scene.getScene('PlazaScene').cameras.main.zoom);
  await page.waitForTimeout(3000);
  const z1 = await page.evaluate(() => window.game.scene.getScene('PlazaScene').cameras.main.zoom);
  checks.zoom_increasing = z1 > z0;
  console.log('zoom', z0, '->', z1);
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
console.log('CHECKS:', JSON.stringify(checks));
process.exit(Object.values(checks).every(v=>v)?0:1);
