// shots/capture.mjs — drive window.__game to canonical vantages and screenshot each.
import { chromium } from 'playwright';
import { mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const OUT = join(__dirname, 'out');
mkdirSync(OUT, { recursive: true });

const URL = process.env.GAME_URL || 'http://localhost:5173/';
const W = 1600, H = 900;

const SHOTS = [
  { name: 'space', preset: ['space', 0] },
  { name: 'entry', preset: ['entry', 0] },
  { name: 'surface', preset: ['surface', 0] },
  { name: 'scan', preset: ['scan', 0] },
  { name: 'planet2', preset: ['planet2', 1] },
];

function waitFrames(page, n = 40) {
  return page.evaluate((count) => new Promise((res) => {
    let i = 0;
    const tick = () => (++i >= count ? res(true) : requestAnimationFrame(tick));
    requestAnimationFrame(tick);
  }), n);
}

const errors = [];
const browser = await chromium.launch({
  headless: true,
  args: ['--use-gl=angle', '--use-angle=swiftshader', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--disable-dev-shm-usage'],
});
const page = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
page.on('console', (m) => { if (m.type() === 'error') errors.push('CONSOLE: ' + m.text()); });
page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));

await page.goto(URL, { waitUntil: 'networkidle' });
await page.waitForFunction(() => !!window.__game, null, { timeout: 20000 });
await waitFrames(page, 30);

const meta = await page.evaluate(() => ({ title: window.__game._title, descs: window.__game._descs }));
console.log('TITLE:', meta.title);
console.log('PLANETS:', JSON.stringify(meta.descs));

for (const s of SHOTS) {
  await page.evaluate(([n, i]) => window.__game.preset(n, i), s.preset);
  await waitFrames(page, 26);
  await new Promise((r) => setTimeout(r, 250));
  await waitFrames(page, 8);
  await page.screenshot({ path: join(OUT, s.name + '.png') });
  const state = await page.evaluate(() => ({ mode: window.__game.mode, phase: window.__game.phase, units: window.__game.units, scans: window.__game.scans }));
  console.log(`shot ${s.name.padEnd(9)} ->`, JSON.stringify(state));
}

if (errors.length) {
  console.log('\n--- PAGE ERRORS ---');
  for (const e of errors.slice(0, 40)) console.log(e);
} else {
  console.log('\nno page errors');
}

await browser.close();
console.log('done. shots in', OUT);
