// smoke.mjs: headless smoke test of the built game.
// Starts vite preview, loads the page, simulates input, collects console errors + screenshots.
import { chromium } from 'playwright';
import { spawn } from 'child_process';

const PORT = 4178;
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) => {
    const s = d.toString();
    if (s.includes('Local:')) { clearTimeout(t); resolve(); }
  });
  server.stderr.on('data', (d) => {
    const s = d.toString();
    if (s.includes('Local:')) { clearTimeout(t); resolve(); }
    if (s.toLowerCase().includes('error')) console.log('SERVER ERR:', s);
  });
});

const errors = [];
const logs = [];
try {
  await waitServer();
  console.log('server up');
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('console', (msg) => {
    const t = msg.type();
    logs.push(`[${t}] ${msg.text()}`);
    if (t === 'error') errors.push(msg.text());
  });
  page.on('pageerror', (err) => { errors.push('PAGEERROR: ' + err.message + '\n' + (err.stack || '')); });

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

  // press Enter to start (default name 小满)
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1500);
  await page.screenshot({ path: 'shots/02_house.png' });

  // move right a bit
  for (let i = 0; i < 15; i++) { await page.keyboard.down('d'); await page.waitForTimeout(60); }
  await page.keyboard.up('d');
  await page.waitForTimeout(300);
  await page.screenshot({ path: 'shots/03_move.png' });

  // open debug
  await page.keyboard.press('Backquote');
  await page.waitForTimeout(300);
  await page.screenshot({ path: 'shots/04_debug.png' });

  // check canvas exists
  const hasCanvas = await page.evaluate(() => !!document.querySelector('canvas'));
  console.log('canvas:', hasCanvas);

  await browser.close();
} catch (e) {
  console.log('TEST_FAIL:', e.message);
  errors.push('TEST_FAIL: ' + e.message);
} finally {
  server.kill('SIGTERM');
}

console.log('=== CONSOLE ERRORS (' + errors.length + ') ===');
errors.slice(0, 30).forEach((e) => console.log(e));
console.log('=== DONE ===');
process.exit(errors.length > 0 ? 1 : 0);
