#!/usr/bin/env bash
# Compress MOV files to ~45MB using ffmpeg two-pass encoding.
# Processes all .mov files in the given directory; skips when .mp4 already exists.
# Usage: ./compress_videos.sh [directory]
# Default: para/static/videos/pickplace_exp1_vids

set -e

TARGET_MB=45
# Leave a bit of headroom for audio/metadata (target slightly under 45MB)
TARGET_BITS=$(( (TARGET_MB - 1) * 8 * 1024 ))  # in kbit total

DIR="${1:-$(dirname "$0")/static/videos/pickplace_exp1_vids}"

if [[ ! -d "$DIR" ]]; then
  echo "Error: directory not found: $DIR"
  exit 1
fi

for input in "$DIR"/*.mov; do
  [[ -f "$input" ]] || continue

  base="${input%.mov}"
  output="${base}.mp4"

  if [[ -f "$output" ]]; then
    echo "Skip (already processed): $(basename "$input") -> $(basename "$output")"
    continue
  fi

  # Get duration in seconds (with decimals)
  duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$input" 2>/dev/null || true)
  if [[ -z "$duration" || ! "$duration" =~ ^[0-9.]+$ ]]; then
    echo "Skip (could not get duration): $input"
    continue
  fi

  # Target video bitrate: use ~95% of total bit budget for video
  video_kbit=$(echo "scale=0; ($TARGET_BITS * 0.95) / $duration" | bc)
  # Ensure reasonable bounds (e.g. 200–8000 kbps)
  if [[ $video_kbit -lt 200 ]]; then
    video_kbit=200
  elif [[ $video_kbit -gt 8000 ]]; then
    video_kbit=8000
  fi

  echo "Compressing: $(basename "$input") (duration ${duration}s, target ~${video_kbit}k)"
  echo "  Pass 1/2..."
  ffmpeg -y -i "$input" -c:v libx264 -b:v "${video_kbit}k" -pass 1 -an -f null - 2>/dev/null
  echo "  Pass 2/2..."
  ffmpeg -y -i "$input" -c:v libx264 -b:v "${video_kbit}k" -pass 2 -c:a aac -b:a 128k "$output" 2>/dev/null

  # Remove ffmpeg pass log (created in cwd)
  rm -f ffmpeg2pass-0.log ffmpeg2pass-0.log.mbtree

  if [[ -f "$output" ]]; then
    size_bytes=$(stat -f%z "$output" 2>/dev/null || stat -c%s "$output" 2>/dev/null)
    size_mb=$(echo "scale=2; $size_bytes / 1048576" | bc)
    echo "  -> $output (${size_mb} MB)"
  fi
done

echo "Done. Outputs are .mp4 alongside each .mov. Re-run to skip already processed files."
