/**
 * Pre-build Remotion Bundle for Packaging
 *
 * This script runs BEFORE electron-forge packages the app.
 * It pre-bundles the Remotion project so the packaged app
 * doesn't need to call bundle() at runtime (which requires
 * webpack and other heavy deps).
 *
 * Usage: node scripts/bundle-remotion.js
 * Output: out/remotion-bundle/
 */
const path = require('path');
const fs = require('fs');

async function main() {
  const outDir = path.join(__dirname, '..', 'out', 'remotion-bundle');

  // Clean previous bundle
  if (fs.existsSync(outDir)) {
    fs.rmSync(outDir, { recursive: true });
  }

  console.log('📦 Building Remotion bundle for packaging...');
  console.log('   Entry: src/Root.tsx');
  console.log('   Output:', outDir);

  const { bundle } = require('@remotion/bundler');
  const entryPoint = path.join(__dirname, '..', 'src', 'Root.tsx');

  const bundlePath = await bundle({
    entryPoint,
    outDir,
    webpackOverride: (config) => config,
  });

  console.log('✅ Remotion bundle ready:', bundlePath);

  // Verify the bundle exists
  const indexPath = path.join(bundlePath, 'index.html');
  if (!fs.existsSync(indexPath)) {
    throw new Error(`Bundle verification failed: ${indexPath} not found`);
  }

  console.log('✅ Bundle verified (index.html exists)');
}

main().catch((err) => {
  console.error('❌ Remotion bundle failed:', err);
  process.exit(1);
});
