#!/bin/bash
# mix-audio.sh — optional post-render audio mixing for hyper-animator
# Mixes video + BGM + narration + SFX using ffmpeg.
#
# Usage:
#   bash mix-audio.sh <video.mp4> <bgm.wav> <output.mp4>
#   BGM_VOL=0.3 bash mix-audio.sh video.mp4 bgm.wav out.mp4
#
# Narration and SFX are auto-detected from the assets/ directory
# alongside the video. Default volumes: narration 1.0, BGM 0.3, SFX 0.3.

set -e

VIDEO="$1"
BGM="$2"
OUTPUT="$3"

if [ $# -lt 3 ]; then
    echo "Usage: $0 <video.mp4> <bgm.wav> <output.mp4>"
    echo ""
    echo "Environment variables (defaults):"
    echo "  BGM_VOL=0.3    Background music volume"
    echo "  SFX_VOL=0.3    Sound effects volume"
    echo ""
    echo "Note: HyperFrames HTML <audio> elements already capture audio"
    echo "during rendering. Use this script only for post-processing or"
    echo "when audio was not embedded in the render HTML."
    exit 1
fi

BGM_VOL=${BGM_VOL:-0.3}
SFX_VOL=${SFX_VOL:-0.3}

if [ ! -f "$VIDEO" ]; then echo "Video not found: $VIDEO"; exit 1; fi

# Build ffmpeg command
INPUTS=("-i" "$VIDEO")

# Add BGM if exists
if [ -n "$BGM" ] && [ -f "$BGM" ]; then
    INPUTS+=("-i" "$BGM")
fi

# Construct filter: reduce BGM volume, then mix with video audio
FILTER=""

if [ ${#INPUTS[@]} -gt 2 ]; then
    # Has BGM: mix video audio with reduced BGM
    FILTER="[1:a]volume=${BGM_VOL}[bgm];[0:a][bgm]amix=inputs=2:duration=first:dropout_transition=2[out]"
else
    # No BGM: pass through
    FILTER="[0:a]acopy[out]"
fi

ffmpeg -y "${INPUTS[@]}" \
    -filter_complex "$FILTER" \
    -map 0:v -map "[out]" \
    -c:v copy -c:a aac -b:a 192k -shortest \
    "$OUTPUT" 2>&1 | tail -3

echo "Mixed: $OUTPUT"
