#!/bin/bash
# stem-stats: Analyze audio stems and output key statistics
# Usage: stem-stats <audio_file> [audio_file2 ...]
#
# Output: duration, RMS, peak levels, bit depth for each file

set -euo pipefail

if [[ $# -eq 0 ]]; then
    echo "Usage: stem-stats <audio_file> [audio_file2 ...]" >&2
    exit 1
fi

printf "%-40s %10s %10s %10s %10s %8s\n" "FILE" "DURATION" "RMS_dB" "PEAK_dB" "RMS_PK_dB" "BITS"
printf "%-40s %10s %10s %10s %10s %8s\n" "----" "--------" "------" "-------" "---------" "----"

for FILE in "$@"; do
    if [[ ! -f "$FILE" ]]; then
        echo "Warning: File not found: $FILE" >&2
        continue
    fi

    stats=$(sox "$FILE" -n stats 2>&1)

    duration=$(echo "$stats" | grep "Length s" | awk '{print $3}')
    rms=$(echo "$stats" | grep "RMS lev dB" | head -1 | awk '{print $4}')
    peak=$(echo "$stats" | grep "Pk lev dB" | head -1 | awk '{print $4}')
    rms_pk=$(echo "$stats" | grep "RMS Pk dB" | head -1 | awk '{print $4}')
    bits=$(echo "$stats" | grep "Bit-depth" | head -1 | awk '{print $2}')

    # Format duration as HH:MM:SS
    dur_int=${duration%.*}
    dur_fmt=$(printf '%02d:%02d:%02d' $((dur_int/3600)) $(((dur_int%3600)/60)) $((dur_int%60)))

    printf "%-40s %10s %10s %10s %10s %8s\n" "$(basename "$FILE")" "$dur_fmt" "$rms" "$peak" "$rms_pk" "$bits"
done
