#!/bin/bash
# mix-normalize: Analyze and normalize audio per-track based on mix.json
# Usage:
#   mix-normalize --from-mix <mixfile.json> --input <audio.wav> [options]
#
# Options:
#   --from-mix FILE    Read track boundaries from mix.json
#   --input FILE       Input audio file to analyze/normalize
#   --target-lufs N    Target LUFS level (default: -14 for streaming)
#   --analyze-only     Just show per-track levels, don't process
#   --output FILE      Output filename (required unless --analyze-only)

set -euo pipefail

MIXFILE=""
INPUT=""
OUTPUT=""
TARGET_LUFS=-14
ANALYZE_ONLY=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --from-mix)
            MIXFILE="$2"
            shift 2
            ;;
        --input)
            INPUT="$2"
            shift 2
            ;;
        --output)
            OUTPUT="$2"
            shift 2
            ;;
        --target-lufs)
            TARGET_LUFS="$2"
            shift 2
            ;;
        --analyze-only)
            ANALYZE_ONLY=true
            shift
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

if [[ -z "$MIXFILE" ]] || [[ -z "$INPUT" ]]; then
    echo "Usage: mix-normalize --from-mix <mixfile.json> --input <audio.wav> [options]" >&2
    exit 1
fi

if [[ "$ANALYZE_ONLY" == false ]] && [[ -z "$OUTPUT" ]]; then
    echo "Error: --output required unless --analyze-only" >&2
    exit 1
fi

echo "=== Per-Track Loudness Analysis ==="
echo "Target: ${TARGET_LUFS} LUFS"
echo ""
printf "%-4s %-22s %8s %8s %8s %8s\n" "#" "TRACK" "START" "END" "LUFS" "ADJUST"
printf "%-4s %-22s %8s %8s %8s %8s\n" "---" "-----" "-----" "---" "----" "------"

# Read tracks and analyze each segment
jq -r '.tracks | sort_by(.id) | .[] | "\(.id)|\(.name)|\(.start_s)|\(.end_s)"' "$MIXFILE" | \
while IFS='|' read -r id name start_s end_s; do
    dur=$((end_s - start_s))

    # Measure LUFS for this segment
    lufs=$(ffmpeg -i "$INPUT" -ss "$start_s" -t "$dur" -af loudnorm=print_format=json -f null - 2>&1 | \
           grep "input_i" | sed 's/.*: "\([^"]*\)".*/\1/' | head -1)

    if [[ -n "$lufs" ]]; then
        adjust=$(echo "$TARGET_LUFS - $lufs" | bc -l)
        printf "%-4s %-22s %8s %8s %8.1f %+8.1f dB\n" "$id" "${name:0:22}" \
               "$(printf '%d:%02d' $((start_s/60)) $((start_s%60)))" \
               "$(printf '%d:%02d' $((end_s/60)) $((end_s%60)))" \
               "$lufs" "$adjust"
    else
        printf "%-4s %-22s %8s %8s %8s %8s\n" "$id" "${name:0:22}" \
               "$(printf '%d:%02d' $((start_s/60)) $((start_s%60)))" \
               "$(printf '%d:%02d' $((end_s/60)) $((end_s%60)))" \
               "ERR" "-"
    fi
done

if [[ "$ANALYZE_ONLY" == true ]]; then
    echo ""
    echo "(analyze-only mode, no processing)"
    exit 0
fi

# For now, just normalize the whole file
# TODO: implement per-segment gain adjustment
echo ""
echo "Normalizing to ${TARGET_LUFS} LUFS..."
ffmpeg -y -i "$INPUT" -af loudnorm=I=${TARGET_LUFS}:TP=-1:LRA=11 "$OUTPUT" 2>/dev/null

echo "Output: $OUTPUT"
