/**
 * Programmatic Render Script
 *
 * Node.js API for rendering videos using @remotion/renderer.
 * Usage: tsx src/render.ts --props=script.json --output=out/video.mp4
 */

import path from 'node:path';
import fs from 'node:fs';
import { bundle } from '@remotion/bundler';
import { renderMedia, selectComposition } from '@remotion/renderer';
import { enableTailwind } from '@remotion/tailwind-v4';

function parseArgs(): { propsPath: string; outputPath: string } {
  const args = process.argv.slice(2);
  let propsPath = '';
  let outputPath = 'out/render.mp4';

  for (const arg of args) {
    if (arg.startsWith('--props=')) {
      propsPath = arg.replace('--props=', '');
    } else if (arg.startsWith('--output=')) {
      outputPath = arg.replace('--output=', '');
    }
  }

  if (!propsPath) {
    console.error('Usage: tsx src/render.ts --props=<script.json> [--output=<output.mp4>]');
    process.exit(1);
  }

  return {
    propsPath: path.resolve(propsPath),
    outputPath: path.resolve(outputPath),
  };
}

async function main() {
  const { propsPath, outputPath } = parseArgs();

  const propsJson = fs.readFileSync(propsPath, 'utf-8');
  const inputProps = { script: JSON.parse(propsJson) };

  console.log(`Bundling project...`);
  const bundleLocation = await bundle({
    entryPoint: path.resolve(__dirname, 'index.ts'),
    webpackOverride: (config) => enableTailwind(config),
  });

  console.log(`Selecting composition...`);
  const composition = await selectComposition({
    serveUrl: bundleLocation,
    id: 'ExpertConversation',
    inputProps,
  });

  const outputDir = path.dirname(outputPath);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  console.log(`Rendering ${composition.width}x${composition.height} @ ${composition.fps}fps, ${composition.durationInFrames} frames...`);
  await renderMedia({
    composition,
    serveUrl: bundleLocation,
    codec: 'h264',
    outputLocation: outputPath,
    inputProps,
  });

  console.log(`Rendered to ${outputPath}`);
}

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