import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4198;
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);
  // go to bakery day 5 to test T11 knead (has choices)
  await page.evaluate(() => {
    window.director.debugSetDay(5);
    const g = window.game;
    g.scene.stop('HouseScene');
    g.scene.start('BakeryScene', { spawn: 'default' });
  });
  await page.waitForTimeout(1000);
  // place player at knead point (tile 3,6 = 56, 104)
  await page.evaluate(() => { window.game.scene.getScene('BakeryScene').player.setPosition(56, 96); });
  await page.waitForTimeout(300);
  await page.keyboard.press('e'); // trigger knead -> choices appear
  await page.waitForTimeout(600);
  // read choices
  const choices = await page.evaluate(() => {
    const ui = window.game.scene.getScene('UIScene');
    return ui.choiceTexts.map(t => t.text);
  });
  console.log('choices:', JSON.stringify(choices));
  checks.choices_3 = choices.filter(c=>c).length === 3;
  checks.has_gentle = choices.some(c=>c.includes('温柔'));
  checks.has_deny = choices.some(c=>c.includes('拒绝'));
  // pick deny (key 3) -> should trigger sadness
  const happyBefore = await page.evaluate(() => window.director.happiness);
  await page.keyboard.press('3');
  await page.waitForTimeout(400);
  const happyAfter = await page.evaluate(() => window.director.happiness);
  checks.deny_lowers_happy = happyAfter === happyBefore - 5;
  console.log('happy', happyBefore, '->', happyAfter);
  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);
