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,600)));
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 });
await new Promise(r=>setTimeout(r,600));
await page.evaluate(() => {
  const sm = window.__game.scene;
  for (const sc of sm.getScenes(true)) { const k = sc.scene.key; if (k !== 'UIScene' && k !== 'PlazaScene') sm.stop(k); }
  sm.start('PlazaScene', { spawn: 'default' });
});
await page.waitForFunction(() => window.__game.scene.isActive('PlazaScene'), { timeout: 9000 });
await new Promise(r=>setTimeout(r,600));

// 路径 A：直接调用 activateInteract('noticeboard')，绕过键盘
const pathA = await page.evaluate(async () => {
  const s = window.__game.scene.getScene('PlazaScene');
  const z = s.interactZones.find(z => z.id === 'noticeboard');
  s.player.setPosition(z.x, z.y + 8); s.player.setVelocity(0, 0);
  let err = null;
  try { s.activateInteract('noticeboard'); } catch (e) { err = String(e && e.stack || e); }
  await new Promise(r => setTimeout(r, 500));
  const u = window.__game.scene.getScene('UIScene');
  return { err, dialogueActive: window.__director.dialogueActive, payload: u.payload ? u.payload.lines : null, body: u.dlgBody ? u.dlgBody.text : null };
});
console.log('pathA(direct call):', JSON.stringify(pathA, null, 1));

// 清掉对话
await page.evaluate(() => window.__director.forceIdle());
await new Promise(r=>setTimeout(r,300));

// 路径 B：合成 DOM 键盘事件
const pathB = await page.evaluate(async () => {
  const fire = (type) => window.dispatchEvent(new KeyboardEvent(type, { code: 'KeyE', key: 'e', keyCode: 69, which: 69, bubbles: true, cancelable: true }));
  fire('keydown');
  await new Promise(r => setTimeout(r, 120));
  fire('keyup');
  await new Promise(r => setTimeout(r, 500));
  const u = window.__game.scene.getScene('UIScene');
  return { dialogueActive: window.__director.dialogueActive, payload: u.payload ? u.payload.lines : null };
});
console.log('pathB(synthetic DOM key):', JSON.stringify(pathB, null, 1));

await page.evaluate(() => window.__director.forceIdle());
await new Promise(r=>setTimeout(r,300));

// 路径 C：puppeteer 键盘（与验收脚本相同），先 dump JustDown 相关状态
await page.keyboard.press('KeyE');
await new Promise(r=>setTimeout(r,500));
const pathC = await page.evaluate(() => {
  const s = window.__game.scene.getScene('PlazaScene');
  const u = window.__game.scene.getScene('UIScene');
  return {
    dialogueActive: window.__director.dialogueActive,
    payload: u.payload ? u.payload.lines : null,
    keyE: s.keyE ? { isDown: s.keyE.isDown, enabled: s.keyE.enabled } : null,
    kbEnabled: s.input.keyboard ? s.input.keyboard.enabled : null,
  };
});
console.log('pathC(puppeteer key):', JSON.stringify(pathC, null, 1));

// 路径 D：talkTo 直调
const pathD = await page.evaluate(async () => {
  const s = window.__game.scene.getScene('PlazaScene');
  let err = null;
  try { s.talkTo('afu'); } catch (e) { err = String(e && e.stack || e); }
  await new Promise(r => setTimeout(r, 500));
  const u = window.__game.scene.getScene('UIScene');
  return { err, dialogueActive: window.__director.dialogueActive, payload: u.payload ? u.payload.lines : null, body: u.dlgBody ? u.dlgBody.text : null };
});
console.log('pathD(talkTo afu):', JSON.stringify(pathD, null, 1));

await browser.close();
