import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4196;
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);
  // set name directly (simulates successful CJK input)
  await page.evaluate(() => { window.director.playerName = '测试员'; });
  await page.evaluate(() => {
    const g = window.game;
    for (const k of ['HouseScene','PlazaScene','BakeryScene','ShopScene','ClinicScene','LakeScene','FieldScene','WellAreaScene','FogBoundaryScene','WhiteLayerScene']) g.scene.stop(k);
    g.scene.stop('UIScene');
    g.scene.start('EndingScene', { ending: 'E3' });
  });
  await page.waitForTimeout(4000);
  const texts = await page.evaluate(() => {
    const end = window.game.scene.getScene('EndingScene');
    return end.children.list.filter(c=>c.text).map(c=>c.text);
  });
  console.log('E3 texts:', JSON.stringify(texts));
  const joined = texts.join('|');
  checks.has_name = joined.includes('姓名：测试员');
  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);
