#!/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/web-embed-frames');

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

async function captureFrames() {
  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: 1280, height: 720 });
  
  const filePath = path.resolve(__dirname, 'web-embed/stripe-simulation.html');
  await page.goto(`file://${filePath}`);
  
  // Wait for animation to start
  await new Promise(r => setTimeout(r, 500));
  
  // Capture 12 seconds at 10fps = 120 frames
  const totalFrames = 120;
  const frameInterval = 100;
  
  for (let i = 0; i < totalFrames; i++) {
    const frameNum = String(i + 1).padStart(3, '0');
    await page.screenshot({ 
      path: path.join(outputDir, `frame-${frameNum}.png`),
      type: 'png'
    });
    if (i % 10 === 0) console.log(`Captured frame ${frameNum}/${totalFrames}`);
    await new Promise(r => setTimeout(r, frameInterval));
  }
  
  await browser.close();
  
  // Create MP4
  console.log('Creating video...');
  const mp4Path = path.join(__dirname, 'output/stripe-web-simulation.mp4');
  
  try {
    execSync(`ffmpeg -y -framerate 10 -i "${outputDir}/frame-%03d.png" -c:v libx264 -pix_fmt yuv420p -crf 23 "${mp4Path}"`, { stdio: 'inherit' });
    console.log(`Video created: ${mp4Path}`);
  } catch (e) {
    console.error('FFmpeg error:', e.message);
  }
}

captureFrames().catch(console.error);
