// Browser. The page's footage as a browser shows it: Chromium plays footage-rift.webm at a tenth of the speed and six
// screenshots are taken as it plays, for footage.py's browser check.
//
//   node --input-type=module - <footage.webm> <out-dir> < research/2026-10-22-starlock-glow/code/footage-browser.mjs.txt
//
// (named .txt because the site serves code/ as text; see README.md)
import { createRequire } from 'node:module';
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';

const require = createRequire(path.join(process.cwd(), 'x.js'));
const { chromium } = (() => {
  for (const id of [process.env.PLAYWRIGHT, 'playwright', '/opt/node-tools/node_modules/playwright'].filter(Boolean)) {
    try { return require(id); } catch {}
  }
  throw new Error('Playwright not found: set PLAYWRIGHT to its path.');
})();
const [video, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const page0 = '<body style="margin:0;background:#000"><video id="v" src="/v.webm" muted playsinline loop style="display:block"></video></body>';
const srv = http.createServer((q, r) => {
  if (q.url === '/v.webm') { r.writeHead(200, { 'Content-Type': 'video/webm' }); fs.createReadStream(video).pipe(r); }
  else { r.writeHead(200, { 'Content-Type': 'text/html' }); r.end(page0); }
}).listen(0);
const port = srv.address().port;
const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  await page.goto(`http://127.0.0.1:${port}/`);
  // play it at a tenth of the speed and take screenshots of the page as it plays: what the browser shows. (A paused
  // seek doesn't present a new frame in headless Chromium, and its frame callbacks don't fire; footage.py matches
  // each screenshot to its source frame by the picture itself.)
  const [w, h] = await page.evaluate(async () => {
    const v = document.getElementById('v');
    if (v.readyState < 2) await new Promise((r) => v.addEventListener('loadeddata', r, { once: true }));
    v.playbackRate = 0.1; await v.play();
    return [v.videoWidth, v.videoHeight];
  });
  await page.setViewportSize({ width: w, height: h });
  for (let k = 0; k < 6; k++) {
    await new Promise((r) => setTimeout(r, 4500));
    await page.screenshot({ path: path.join(out, `b${String(k).padStart(4, '0')}.png`), clip: { x: 0, y: 0, width: w, height: h } });
  }
} finally { await browser.close(); srv.close(); }
