#!/usr/bin/env node
import puppeteer from 'puppeteer';
import { execSync } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const outputDir = path.join(__dirname, 'output/demo-frames');
const htmlFile = path.join(__dirname, 'output/mcp-demo.html');

fs.rmSync(outputDir, { recursive: true, force: true });
fs.mkdirSync(outputDir, { recursive: true });

async function capture() {
  const browser = await puppeteer.launch({ 
    headless: true,
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    args: ['--no-sandbox']
  });
  
  const page = await browser.newPage();
  await page.setViewport({ width: 1920, height: 1080 });
  
  const fps = 30;
  const duration = 10;
  const totalFrames = fps * duration;
  
  console.log(`Capturing ${totalFrames} frames...`);
  
  await page.goto(`file://${htmlFile}`, { waitUntil: 'networkidle0' });
  await new Promise(r => setTimeout(r, 500));
  
  for (let i = 0; i < totalFrames; i++) {
    const scroll = i / (totalFrames - 1);
    await page.evaluate(s => window.updateScene(s), scroll);
    await new Promise(r => setTimeout(r, 20));
    
    await page.screenshot({ 
      path: path.join(outputDir, `frame-${String(i+1).padStart(4,'0')}.png`),
      type: 'png'
    });
    
    if (i % 30 === 0) console.log(`${Math.round(scroll*100)}%`);
  }
  
  await browser.close();
  
  console.log('Encoding...');
  const mp4 = path.join(__dirname, 'output/mcp-demo.mp4');
  execSync(`ffmpeg -y -framerate ${fps} -i "${outputDir}/frame-%04d.png" -c:v libx264 -pix_fmt yuv420p -crf 18 "${mp4}"`, { stdio: 'inherit' });
  console.log(`✓ ${mp4}`);
}

capture().catch(console.error);
