#!/usr/bin/env node
/**
 * Capture animation frames and create GIF
 */

import puppeteer from 'puppeteer';
import { execSync } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const htmlFile = process.argv[2] || 'output/stripe-animation.html';
const outputDir = path.join(__dirname, 'output/stripe-frames');

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: 1920, height: 1080 });
  
  // Load page
  const filePath = path.resolve(__dirname, htmlFile);
  await page.goto(`file://${filePath}`);
  
  // Capture frames at key moments
  const frames = [
    { delay: 0, name: '01' },
    { delay: 200, name: '02' },
    { delay: 400, name: '03' },
    { delay: 600, name: '04' },
    { delay: 800, name: '05' },
    { delay: 1000, name: '06' },
    { delay: 1200, name: '07' },
    { delay: 1400, name: '08' },
    { delay: 1600, name: '09' },
    { delay: 1800, name: '10' },
    { delay: 2000, name: '11' },
    { delay: 2200, name: '12' },
  ];
  
  for (const frame of frames) {
    await new Promise(r => setTimeout(r, frame.delay === 0 ? 0 : 200));
    await page.screenshot({ 
      path: path.join(outputDir, `frame-${frame.name}.png`),
      type: 'png'
    });
    console.log(`Captured frame ${frame.name}`);
  }
  
  await browser.close();
  
  // Create GIF using ffmpeg
  console.log('Creating GIF...');
  try {
    execSync(`ffmpeg -y -framerate 5 -i ${outputDir}/frame-%02d.png -vf "scale=960:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" ${outputDir}/../stripe-animation.gif`, { stdio: 'inherit' });
    console.log('GIF created: output/stripe-animation.gif');
  } catch (e) {
    console.error('FFmpeg failed, trying convert...', e.message);
    try {
      execSync(`convert -delay 20 -loop 0 ${outputDir}/frame-*.png ${outputDir}/../stripe-animation.gif`, { stdio: 'inherit' });
      console.log('GIF created with ImageMagick');
    } catch (e2) {
      console.error('ImageMagick also failed:', e2.message);
    }
  }
}

captureFrames().catch(console.error);
