import puppeteer from 'puppeteer-core';
import { spawn } from 'node:child_process';
import net from 'node:net';
const preview = spawn('npx', ['vite','preview','--host','127.0.0.1','--port','4815','--strictPort'], { stdio:'ignore' });
process.on('exit', () => { try{preview.kill()}catch{} });
for (let i=0;i<50;i++){ const ok = await new Promise(r=>{const s=net.connect(4815,'127.0.0.1');s.once('connect',()=>{s.end();r(true)});s.once('error',()=>r(false))}); if(ok)break; await new Promise(r=>setTimeout(r,300)); }
const browser = await puppeteer.launch({ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true, args: ['--autoplay-policy=no-user-gesture-required','--mute-audio'] });
const page = await browser.newPage();
await page.setViewport({ width: 960, height: 560 });
page.on('pageerror', e => console.log('[pageerror]', (e.stack||e.message).slice(0,400)));
await page.goto('http://127.0.0.1:4815/', { waitUntil: 'networkidle2' });
await page.waitForFunction('window.__game && window.__director', { timeout: 20000 });
await page.waitForFunction(() => window.__game.scene.isActive('TitleScene'), { timeout: 20000 });
await page.evaluate(() => { document.querySelector('#game input[type="text"]').closest('div').querySelector('button').click(); });
await page.waitForFunction(() => window.__game.scene.isActive('HouseScene'), { timeout: 15000 });
const sleep = (ms) => new Promise(r=>setTimeout(r,ms));
await sleep(600);
// 依次跳转地图并截图
for (const [sceneKey, spawn] of [['HouseScene','default'],['PlazaScene','default'],['FieldScene','default'],['WellScene','default'],['LakeScene','default']]) {
  await page.evaluate(([k, sp]) => {
    const sm = window.__game.scene;
    for (const sc of sm.getScenes(true)) { const kk = sc.scene.key; if (kk !== 'UIScene' && kk !== k) sm.stop(kk); }
    sm.start(k, { spawn: sp });
  }, [sceneKey, spawn]);
  await page.waitForFunction((k) => window.__game.scene.isActive(k), { timeout: 9000 }, sceneKey);
  await sleep(900);
  await page.screenshot({ path: `tools/shots/fix_${sceneKey}.png` });
  console.log('shot', sceneKey);
}
await browser.close();
process.exit(0);
