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));
const active = (k) => page.evaluate((k) => window.__game.scene.isActive(k), k);
const tap = async (code, hold=90) => { await page.keyboard.down(code); await sleep(hold); await page.keyboard.up(code); await sleep(30); };
// 清掉开场对话
for (let i = 0; i < 8; i++) {
  const open = await page.evaluate(() => { const u = window.__game.scene.getScene('UIScene'); return !!(u && u.payload); });
  if (!open) break;
  await tap('KeyE'); await sleep(200);
}
await sleep(300);

// 1) 从小屋自然走出去：先右移对齐门（x=152），再向下穿出
await page.keyboard.down('KeyD'); await sleep(420); await page.keyboard.up('KeyD');
await page.keyboard.down('KeyS'); await sleep(800); await page.keyboard.up('KeyS');
await page.waitForFunction(() => window.__game.scene.isActive('PlazaScene'), { timeout: 9000 });
console.log('出门 → PlazaScene OK');
// 2) 等待 2 秒：不得回弹
await sleep(2000);
const still = await active('PlazaScene');
const houseBack = await active('HouseScene');
console.log('2 秒后仍在广场:', still, '| 弹回小屋:', houseBack, still && !houseBack ? 'PASS' : 'FAIL');
// 3) 立即折返：向上走回门里（落点 24px 已武装，应可正常回屋）
await page.keyboard.down('KeyW'); await sleep(900); await page.keyboard.up('KeyW');
await sleep(800);
const backHome = await active('HouseScene');
console.log('折返回家:', backHome ? 'PASS' : 'FAIL');
await browser.close();
process.exit(0);
