// smoke2.mjs: deeper smoke test — walk to door, enter plaza, talk to NPC, check debug, force ending.
import { chromium } from 'playwright';
import { spawn } from 'child_process';

const PORT = 4179;
const server = spawn('node', ['node_modules/vite/bin/vite.js', 'preview', '--port', String(PORT), '--strictPort'], {
  cwd: process.cwd(), stdio: 'pipe',
});
const waitServer = () => new Promise((resolve, reject) => {
  const t = setTimeout(() => reject(new Error('server timeout')), 30000);
  server.stdout.on('data', (d) => { if (d.toString().includes('Local:')) { clearTimeout(t); resolve(); } });
  server.stderr.on('data', (d) => { if (d.toString().includes('Local:')) { clearTimeout(t); resolve(); } });
});

const errors = [];
try {
  await waitServer();
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('console', (msg) => { if (msg.type() === 'error') errors.push(msg.text()); });
  page.on('pageerror', (err) => { errors.push('PAGEERROR: ' + err.message); });

  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);
  await page.screenshot({ path: 'shots/s2_01_title.png' });

  // start
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1000);
  await page.screenshot({ path: 'shots/s2_02_house.png' });

  // walk down to door (door_plaza at tile 5,7 bottom)
  for (let i = 0; i < 20; i++) { await page.keyboard.down('s'); await page.waitForTimeout(50); }
  await page.keyboard.up('s');
  await page.waitForTimeout(200);
  // press E to enter door
  await page.keyboard.press('e');
  await page.waitForTimeout(1000);
  await page.screenshot({ path: 'shots/s2_03_plaza.png' });

  // walk right a bit then interact
  for (let i = 0; i < 10; i++) { await page.keyboard.down('d'); await page.waitForTimeout(50); }
  await page.keyboard.up('d');
  await page.waitForTimeout(200);
  await page.keyboard.press('e');
  await page.waitForTimeout(800);
  await page.screenshot({ path: 'shots/s2_04_talk.png' });

  // advance dialogue
  await page.keyboard.press('e');
  await page.waitForTimeout(400);

  // open debug, force ending E3
  await page.keyboard.press('Backquote');
  await page.waitForTimeout(300);
  await page.screenshot({ path: 'shots/s2_05_debug.png' });
  // click the E3 force button by text
  const e3btn = await page.getByText('强制结局 E3 (苏醒)').first();
  if (e3btn) { await e3btn.click(); await page.waitForTimeout(2500); }
  await page.screenshot({ path: 'shots/s2_06_endingE3.png' });

  await browser.close();
} catch (e) {
  errors.push('TEST_FAIL: ' + e.message);
} finally {
  server.kill('SIGTERM');
}
console.log('=== ERRORS (' + errors.length + ') ===');
errors.slice(0, 20).forEach((e) => console.log(e));
console.log('=== DONE ===');
process.exit(errors.length > 0 ? 1 : 0);
