#!/bin/bash
set -e

cd /Users/jakeshore/.clawdbot/workspace/surya-manim-v2
MANIM=/Users/jakeshore/.clawdbot/workspace/surya-manim-journey/venv/bin/manim

OUTPUT_DIR="./output"
mkdir -p "$OUTPUT_DIR"

echo "=== SURYA EPIC RENDER STARTED ==="
echo "Time: $(date)"

# Function to process a track
process_track() {
    TRACK=$1
    AUDIO=$2
    
    VIDEO_FILE="./media/videos/surya_epic/480p30/${TRACK}.mp4"
    AUDIO_FILE="./audio/${AUDIO}"
    FINAL_FILE="${OUTPUT_DIR}/${TRACK}_final.mp4"
    
    echo ""
    echo "=== Processing $TRACK ==="
    
    # Check if already rendered
    if [ -f "$VIDEO_FILE" ]; then
        echo "Video already exists: $VIDEO_FILE"
    else
        echo "Rendering $TRACK..."
        $MANIM -ql --fps 30 --disable_caching surya_epic.py "$TRACK" || {
            echo "ERROR: Failed to render $TRACK"
            return 1
        }
    fi
    
    # Combine with audio
    if [ -f "$FINAL_FILE" ]; then
        echo "Final file already exists: $FINAL_FILE"
    else
        echo "Combining $TRACK with audio..."
        ffmpeg -y -i "$VIDEO_FILE" -i "$AUDIO_FILE" -c:v copy -c:a aac -shortest "$FINAL_FILE" || {
            echo "ERROR: Failed to combine audio for $TRACK"
            return 1
        }
    fi
    
    echo "Completed: $TRACK"
    return 0
}

# Process all tracks
process_track Track01Skin 01_skin.mp3
process_track Track02USavedMe 02_u_saved_me.mp3
process_track Track03Nothing 03_nothing.mp3
process_track Track04SweetRelief 04_sweet_relief.mp3
process_track Track05Tiptoe 05_tiptoe.mp3
process_track Track06NaturesCall 06_natures_call.mp3
process_track Track07Dreamcatcher 07_dreamcatcher.mp3
process_track Track08IDK 08_idk.mp3
process_track Track09WithU 09_with_u.mp3
process_track Track10PoorYou 10_poor_you.mp3
process_track Track11Wait4U 11_wait_4_u.mp3
process_track Track12RunToU 12_run_to_u.mp3
process_track Track13Medications 13_medications.mp3
process_track Track14Hollow 14_hollow.mp3

echo ""
echo "=== Creating concat list ==="
cd "$OUTPUT_DIR"
cat > concat_list.txt << 'EOF'
file 'Track01Skin_final.mp4'
file 'Track02USavedMe_final.mp4'
file 'Track03Nothing_final.mp4'
file 'Track04SweetRelief_final.mp4'
file 'Track05Tiptoe_final.mp4'
file 'Track06NaturesCall_final.mp4'
file 'Track07Dreamcatcher_final.mp4'
file 'Track08IDK_final.mp4'
file 'Track09WithU_final.mp4'
file 'Track10PoorYou_final.mp4'
file 'Track11Wait4U_final.mp4'
file 'Track12RunToU_final.mp4'
file 'Track13Medications_final.mp4'
file 'Track14Hollow_final.mp4'
EOF

echo "=== Concatenating all tracks ==="
ffmpeg -y -f concat -safe 0 -i concat_list.txt -c copy surya_full.mp4 || {
    echo "ERROR: Failed to concatenate tracks"
    exit 1
}

echo ""
echo "=== RENDER COMPLETE ==="
echo "Final file: ${OUTPUT_DIR}/surya_full.mp4"
echo "Time: $(date)"
ls -la surya_full.mp4
