#!/bin/bash
# =============================================================================
# SURYA Epic Manim Render Script
# Renders all 14 tracks and combines with audio
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

AUDIO_DIR="$SCRIPT_DIR/audio"
OUTPUT_DIR="$SCRIPT_DIR/output"
MEDIA_DIR="$SCRIPT_DIR/media/videos/surya_epic/1080p60"

mkdir -p "$OUTPUT_DIR"

# Quality settings
QUALITY="-pqh --fps 60"  # High quality 1080p60
# QUALITY="-pql --fps 30"  # Low quality for testing

# Track classes in order
TRACKS=(
    "Track01Skin:01_skin"
    "Track02USavedMe:02_u_saved_me"
    "Track03Nothing:03_nothing"
    "Track04SweetRelief:04_sweet_relief"
    "Track05Tiptoe:05_tiptoe"
    "Track06NaturesCall:06_natures_call"
    "Track07Dreamcatcher:07_dreamcatcher"
    "Track08IDK:08_idk"
    "Track09WithU:09_with_u"
    "Track10PoorYou:10_poor_you"
    "Track11Wait4U:11_wait_4_u"
    "Track12RunToU:12_run_to_u"
    "Track13Medications:13_medications"
    "Track14Hollow:14_hollow"
)

echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║           SURYA - Epic Manim Render Pipeline                  ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo ""

# Function to render a single track
render_track() {
    local track_info="$1"
    local class_name="${track_info%%:*}"
    local audio_name="${track_info##*:}"
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🎬 Rendering: $class_name"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Render video
    manim $QUALITY surya_epic.py "$class_name" 2>&1 | tail -20
    
    # Find the rendered video
    local video_file=$(find "$MEDIA_DIR" -name "${class_name}.mp4" 2>/dev/null | head -1)
    
    if [ -f "$video_file" ]; then
        echo "✓ Video rendered: $video_file"
        
        # Combine with audio
        local audio_file="$AUDIO_DIR/${audio_name}.mp3"
        local output_file="$OUTPUT_DIR/${audio_name}_final.mp4"
        
        if [ -f "$audio_file" ]; then
            echo "🔊 Adding audio: $audio_file"
            ffmpeg -y -i "$video_file" -i "$audio_file" \
                -c:v copy -c:a aac -b:a 192k \
                -shortest \
                "$output_file" 2>/dev/null
            echo "✓ Output: $output_file"
        else
            echo "⚠ Audio not found: $audio_file"
            cp "$video_file" "$output_file"
        fi
    else
        echo "✗ Video not found for $class_name"
    fi
    
    echo ""
}

# Parse arguments
if [ "$1" == "--single" ] && [ -n "$2" ]; then
    # Render single track
    for track in "${TRACKS[@]}"; do
        if [[ "$track" == *"$2"* ]]; then
            render_track "$track"
            exit 0
        fi
    done
    echo "Track not found: $2"
    echo "Available tracks:"
    for track in "${TRACKS[@]}"; do
        echo "  - ${track%%:*}"
    done
    exit 1
fi

if [ "$1" == "--list" ]; then
    echo "Available tracks:"
    for i in "${!TRACKS[@]}"; do
        echo "  $((i+1)). ${TRACKS[$i]%%:*}"
    done
    exit 0
fi

if [ "$1" == "--combine-only" ]; then
    echo "Combining existing videos with audio..."
    for track in "${TRACKS[@]}"; do
        class_name="${track%%:*}"
        audio_name="${track##*:}"
        
        video_file=$(find "$MEDIA_DIR" -name "${class_name}.mp4" 2>/dev/null | head -1)
        audio_file="$AUDIO_DIR/${audio_name}.mp3"
        output_file="$OUTPUT_DIR/${audio_name}_final.mp4"
        
        if [ -f "$video_file" ] && [ -f "$audio_file" ]; then
            echo "🔊 Combining: $class_name"
            ffmpeg -y -i "$video_file" -i "$audio_file" \
                -c:v copy -c:a aac -b:a 192k \
                -shortest \
                "$output_file" 2>/dev/null
            echo "✓ $output_file"
        fi
    done
    exit 0
fi

if [ "$1" == "--concat" ]; then
    echo "Creating full album video..."
    
    # Create concat list
    concat_file="$OUTPUT_DIR/concat_list.txt"
    > "$concat_file"
    
    for track in "${TRACKS[@]}"; do
        audio_name="${track##*:}"
        video_file="$OUTPUT_DIR/${audio_name}_final.mp4"
        if [ -f "$video_file" ]; then
            echo "file '$video_file'" >> "$concat_file"
        fi
    done
    
    ffmpeg -y -f concat -safe 0 -i "$concat_file" \
        -c copy \
        "$OUTPUT_DIR/SURYA_Full_Album.mp4"
    
    echo "✓ Full album: $OUTPUT_DIR/SURYA_Full_Album.mp4"
    exit 0
fi

# Default: render all tracks
echo "Rendering all 14 tracks..."
echo ""

for track in "${TRACKS[@]}"; do
    render_track "$track"
done

echo "═══════════════════════════════════════════════════════════════"
echo "✓ All tracks rendered!"
echo ""
echo "To create full album video, run:"
echo "  ./render.sh --concat"
echo "═══════════════════════════════════════════════════════════════"
