// Smoke check: serve dist/, load the page headless, assert canvas exists,
// no console/page errors after 3s, and report rAF-measured FPS.
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PORT = 8741;

const server = spawn('python3', ['-m', 'http.server', String(PORT), '--bind', '127.0.0.1'], {
  cwd: path.join(root, 'dist'),
  stdio: 'ignore',
});

const fail = (msg) => {
  console.error(`FAIL: ${msg}`);
  server.kill();
  process.exit(1);
};

try {
  await new Promise((r) => setTimeout(r, 800));

  const browser = await chromium.launch({
    args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
  });
  const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });

  const errors = [];
  page.on('console', (m) => {
    if (m.type() === 'error') errors.push(`console.error: ${m.text()}`);
  });
  page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));

  const resp = await page.goto(`http://127.0.0.1:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  if (!resp || !resp.ok()) fail(`page load status ${resp && resp.status()}`);

  await page.waitForTimeout(3000);

  const canvas = await page.evaluate(() => {
    const c = document.querySelector('canvas');
    return c ? { w: c.width, h: c.height } : null;
  });
  if (!canvas) fail('no canvas element found');
  if (canvas.w === 0 || canvas.h === 0) fail('canvas has zero size');

  if (errors.length) fail(`errors after 3s:\n  ${errors.join('\n  ')}`);

  // FPS sample over 2s (note: headless swiftshader is NOT representative of
  // real-GPU performance — this just proves the loop runs)
  const fps = await page.evaluate(
    () =>
      new Promise((resolve) => {
        let frames = 0;
        const t0 = performance.now();
        const tick = () => {
          frames++;
          if (performance.now() - t0 < 2000) requestAnimationFrame(tick);
          else resolve(frames / ((performance.now() - t0) / 1000));
        };
        requestAnimationFrame(tick);
      })
  );

  await page.screenshot({ path: path.join(root, 'check', 'screenshot.png') });
  await browser.close();

  console.log(`PASS: canvas ${canvas.w}x${canvas.h}, no console errors after 3s`);
  console.log(`INFO: headless (software GL) fps ≈ ${fps.toFixed(1)}`);
  console.log('INFO: screenshot at check/screenshot.png');
  server.kill();
  process.exit(0);
} catch (e) {
  fail(e.stack || String(e));
}
