#!/usr/bin/env node
/**
 * tools/prerender.mjs — 360° turntable pre-render → animated WebP placeholder (PLAN P4-3).
 *
 * Loads the running viewer (?model=<asset>) in headless Chrome, orbits the
 * camera one full turn in N steps, screenshots each frame, then assembles the
 * PNG sequence into an animated WebP via ffmpeg. The result is an SSR
 * placeholder image that hydrates into the live canvas on load.
 *
 * USAGE
 *   node tools/prerender.mjs --asset /samples/Duck.glb [--frames 36] [--size 512] \
 *                           [--framerate 20] [--out public/previews/Duck.webp] \
 *                           [--url http://127.0.0.1:4173]
 *
 * Requires: puppeteer-core (installed) + ffmpeg on PATH + the viewer built & served
 *           (`npm run build && npm run preview`, or `npm run dev`).
 */
import puppeteer from 'puppeteer-core';
import { existsSync, mkdirSync, rmSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..');

const CHROME_CANDIDATES = [
  'C:/Program Files/Google/Chrome/Application/chrome.exe',
  'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
];
function findBrowser() {
  if (process.env.PUPPETEER_EXECUTABLE_PATH && existsSync(process.env.PUPPETEER_EXECUTABLE_PATH)) {
    return process.env.PUPPETEER_EXECUTABLE_PATH;
  }
  for (const p of CHROME_CANDIDATES) if (existsSync(p)) return p;
  return null;
}

function parseArgs(argv) {
  const a = argv.slice(2);
  const o = { asset: null, frames: 36, size: 512, framerate: 20, out: null, url: 'http://127.0.0.1:4173' };
  for (let i = 0; i < a.length; i++) {
    const k = a[i], v = a[i + 1];
    if (k === '--asset') { o.asset = v; i++; }
    else if (k === '--frames') { o.frames = parseInt(v, 10); i++; }
    else if (k === '--size') { o.size = parseInt(v, 10); i++; }
    else if (k === '--framerate') { o.framerate = parseInt(v, 10); i++; }
    else if (k === '--out') { o.out = v; i++; }
    else if (k === '--url') { o.url = v; i++; }
    else if (k === '-h' || k === '--help') return { help: true };
  }
  if (!o.asset) return { help: true };
  if (!o.out) {
    const base = o.asset.split('/').pop().replace(/\.(glb|gltf|obj|fbx|dae|ifc)$/i, '');
    o.out = 'public/previews/' + base + '.webp';
  }
  // Undo MSYS/Git-Bash mangling of leading-slash args (/samples/x.glb -> C:/.../Git/samples/x.glb)
  o.asset = o.asset.replace(/^.*\/Program Files\/Git\//i, '/');
  if (!o.asset.startsWith('/')) o.asset = '/' + o.asset;
  return o;
}

function ffmpegAvailable() {
  try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; }
  catch { return false; }
}

async function main() {
  const opts = parseArgs(process.argv);
  if (opts.help) {
    console.error('Usage: node tools/prerender.mjs --asset /samples/Duck.glb [--frames 36] [--size 512] [--framerate 20] [--out public/previews/Duck.webp] [--url URL]');
    process.exit(opts.asset ? 0 : 1);
  }

  const exe = findBrowser();
  if (!exe) { console.error('[prerender] No Chrome/Edge found.'); process.exit(1); }
  const haveFfmpeg = ffmpegAvailable();

  const baseName = opts.asset.split('/').pop().replace(/\.(glb|gltf|obj|fbx|dae|ifc)$/i, '');
  const frameDir = resolve(root, '.prerender-frames', baseName);
  rmSync(frameDir, { recursive: true, force: true });
  mkdirSync(frameDir, { recursive: true });

  const browser = await puppeteer.launch({
    executablePath: exe,
    headless: 'new',
    args: ['--no-sandbox', '--use-gl=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'],
    defaultViewport: { width: opts.size, height: opts.size },
  });
  const page = await browser.newPage();
  page.on('console', (m) => { if (m.type() === 'error') console.error('[page-console]', m.text()); });
  page.on('pageerror', (e) => console.error('[page-error]', e.message));
  page.on('requestfailed', (r) => console.error('[req-failed]', r.url(), r.failure()?.errorText));
  await page.evaluateOnNewDocument(() => {
    window.__hmwReady = null;
    window.addEventListener('hmw:ready', (e) => { window.__hmwReady = e.detail; });
  });
  await page.goto(opts.url + '?model=' + opts.asset, { waitUntil: 'domcontentloaded', timeout: 30000 });
  await page.waitForFunction('window.__hmwReady != null', { timeout: 30000 });

  for (let i = 0; i < opts.frames; i++) {
    const azimuth = (i / opts.frames) * Math.PI * 2;
    await page.evaluate((az) => window.__viewer && window.__viewer.rotateTo(az), azimuth);
    const file = resolve(frameDir, 'frame_' + String(i).padStart(3, '0') + '.png');
    await page.screenshot({ path: file, omitBackground: false });
  }
  await browser.close();
  const { readdirSync } = await import('node:fs');
  const frameCount = readdirSync(frameDir).filter((f) => f.endsWith('.png')).length;
  console.log('[prerender] captured ' + frameCount + '/' + opts.frames + ' frames -> ' + frameDir);

  const outAbs = resolve(root, opts.out);
  mkdirSync(dirname(outAbs), { recursive: true });

  if (!haveFfmpeg) {
    console.warn('[prerender] ffmpeg not found. Frames left in ' + frameDir);
    console.warn('[prerender] assemble manually:');
    console.warn('  ffmpeg -framerate ' + opts.framerate + ' -i ' + frameDir + '/frame_%03d.png -loop 0 ' + outAbs);
    return;
  }
  // Assemble animated WebP. NOTE: libwebp_anim is broken in this ffmpeg build
  // (outputs 1 frame); -c:v libwebp + -vsync vfr produces correct multi-frame WebP.
  execFileSync('ffmpeg', [
    '-y', '-framerate', String(opts.framerate), '-vsync', 'vfr',
    '-i', resolve(frameDir, 'frame_%03d.png'),
    '-vf', 'scale=' + opts.size + ':' + opts.size + ':flags=lanczos',
    '-c:v', 'libwebp', '-loop', '0', '-lossless', '0', '-q:v', '70',
    outAbs,
  ], { stdio: 'inherit' });
  console.log('[prerender] animated WebP -> ' + opts.out);
  rmSync(frameDir, { recursive: true, force: true });
}

main().catch((e) => {
  console.error('[prerender] Fatal: ' + (e && e.stack ? e.stack : e));
  process.exit(1);
});
