// dbg17：睡觉卡死候选根因验证
// (a) 床淡出期间庆典触发 → celebrationActive 卡死 / 对话 resolver 被覆盖
// (b) 床淡出期间玩家移动 30px 再按 E → 二次触发床 → 双 scene.start
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,500)));
page.on('console', m => { if (m.type()==='error') console.log('[console.error]', m.text().slice(0,300)); });
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 tap = async (code, hold=90) => { await page.keyboard.down(code); await sleep(hold); await page.keyboard.up(code); await sleep(30); };
const ev = (fn, ...a) => page.evaluate(fn, ...a);
const dlgOpen = () => ev(() => { const u = window.__game.scene.getScene('UIScene'); return !!(u && u.payload); });
const state = (tag) => ev((tag) => {
  const sm = window.__game.scene;
  const d = window.__director;
  const s = sm.getScene('HouseScene');
  const door = s && s.doors ? s.doors[0] : null;
  const pd = door && s.player ? { px: +s.player.x.toFixed(0), py: +(s.player.y - 8).toFixed(0),
    dist: +Math.hypot(s.player.x - door.x, (s.player.y - 8) - door.y).toFixed(1),
    armed: s.armedDoors.has(door), trans: s.transitioning } : null;
  return { tag, active: sm.getScenes(true).map(sc => sc.scene.key), day: d.day,
    dlg: d.dialogueActive, celeb: d.celebrationActive, happy: d.happiness,
    ui: (() => { const u = sm.getScene('UIScene'); return u && u.payload ? (u.payload.lines?.[0] ?? '').slice(0, 18) : null; })(),
    pd };
}, tag).then(s => console.log(JSON.stringify(s)));
async function drain(maxIter = 20) {
  for (let i = 0; i < maxIter; i++) { if (!(await dlgOpen())) break; await tap('KeyE'); await sleep(160); }
}
async function setPlayer(k, x, y) {
  await ev((k,x,y) => { const s = window.__game.scene.getScene(k); s.player.setPosition(x, y); s.player.setVelocity(0,0); }, k, x, y);
  await sleep(120);
}
await sleep(600);
const bed = await ev(() => window.__game.scene.getScene('HouseScene').interactZones.find(z => z.id === 'bed'));

console.log('\n=== (a) 床淡出期间庆典触发 ===');
// 低幸福 + 低幸福计时逼近阈值；强制可睡觉
await ev(() => {
  const d = window.__director;
  d.setHappiness(20);
  d.lowHappyMs = 119900;
  d.dayElapsedMs = 300000;
});
// 按 E 睡觉 → 淡出 400ms 内 tick 必触发庆典
await setPlayer('HouseScene', bed.x, bed.y + 8);
await tap('KeyE');
for (let i = 0; i < 12; i++) { await sleep(500); await state(`a t+${(i+1)*0.5}s`); if (await dlgOpen()) await tap('KeyE'); }
// 尝试走到门边逃脱（门在 (88,104)）
await state('a 结束，尝试过门');
await setPlayer('HouseScene', 88 + 30, 104);
await setPlayer('HouseScene', 88, 104);
await sleep(1500);
await state('a 过门后');

console.log('\n=== (b) 床淡出期间二次触发 ===');
await ev(() => {
  const sm = window.__game.scene;
  for (const sc of sm.getScenes(true)) { const k = sc.scene.key; if (k !== 'UIScene' && k !== 'HouseScene') sm.stop(k); }
  sm.start('HouseScene', { spawn: 'default' });
});
await page.waitForFunction(() => window.__game.scene.isActive('HouseScene'), { timeout: 9000 });
await sleep(500);
await drain();
await ev(() => { window.__director.dayElapsedMs = 300000; });
const bed2 = await ev(() => window.__game.scene.getScene('HouseScene').interactZones.find(z => z.id === 'bed'));
await setPlayer('HouseScene', bed2.x, bed2.y + 8);
await tap('KeyE');               // 第一次：触发床，淡出开始
await sleep(150);
await setPlayer('HouseScene', bed2.x + 40, bed2.y + 8); // 移动 >30px 使 spent 重武装
await tap('KeyE');               // 第二次：可能二次触发床
for (let i = 0; i < 10; i++) { await sleep(500); await state(`b t+${(i+1)*0.5}s`); if (await dlgOpen()) await tap('KeyE'); }
await browser.close();
process.exit(0);
