#!/bin/bash

# WebM FPS Analyzer Script
# Analyzes FPS of all WebM files in specified directory (or current directory)

# Usage function
usage() {
    echo "Usage: $0 [directory_path]"
    echo "  directory_path: Path to directory containing WebM files (optional, defaults to current directory)"
    echo ""
    echo "Examples:"
    echo "  $0                                    # Analyze current directory"
    echo "  $0 /path/to/webm/files               # Analyze specific directory"
    echo "  $0 ~/Videos                          # Analyze home Videos directory"
}

# Check if ffprobe is available
if ! command -v ffprobe &> /dev/null; then
    echo "Error: ffprobe is not installed or not in PATH"
    echo "Please install ffmpeg to use this script"
    exit 1
fi

# Handle command line arguments
if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
    usage
    exit 0
fi

# Set target directory
if [[ -n "$1" ]]; then
    target_dir="$1"
    # Expand tilde if present
    target_dir="${target_dir/#\~/$HOME}"

    # Check if directory exists
    if [[ ! -d "$target_dir" ]]; then
        echo "Error: Directory '$target_dir' does not exist"
        exit 1
    fi

    # Check if directory is readable
    if [[ ! -r "$target_dir" ]]; then
        echo "Error: Directory '$target_dir' is not readable"
        exit 1
    fi
else
    target_dir="."
fi

# Initialize variables
declare -a fps_values=()
declare -a filenames=()
total_fps=0
count=0
min_fps=""
max_fps=""

echo "Analyzing WebM files in directory: $target_dir"
echo "========================================"

# Find all .webm files and process them
for file in "$target_dir"/*.webm; do
    # Check if any .webm files exist
    if [[ ! -e "$file" ]]; then
        echo "No WebM files found in directory: $target_dir"
        exit 0
    fi

    # Get just the filename for display
    filename=$(basename "$file")

    echo "Processing: $filename"

    # Extract FPS using ffprobe
    fps=$(ffprobe -v quiet -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 "$file" 2>/dev/null)

    # Check if fps extraction was successful
    if [[ -z "$fps" ]]; then
        echo "  ⚠️  Could not determine FPS for $filename"
        continue
    fi

    # Convert fraction to decimal if needed (e.g., "30/1" to "30")
    if [[ "$fps" == *"/"* ]]; then
        # Use bc for floating point division if available, otherwise use awk
        if command -v bc &> /dev/null; then
            fps_decimal=$(echo "scale=3; $fps" | bc)
        else
            fps_decimal=$(awk "BEGIN {printf \"%.3f\", $fps}")
        fi
    else
        fps_decimal="$fps"
    fi

    echo "  📊 FPS: $fps_decimal"

    # Store values
    fps_values+=("$fps_decimal")
    filenames+=("$filename")

    # Update statistics
    if [[ -z "$min_fps" ]] || (( $(echo "$fps_decimal < $min_fps" | awk '{print ($1 < $2)}') )); then
        min_fps="$fps_decimal"
    fi

    if [[ -z "$max_fps" ]] || (( $(echo "$fps_decimal > $max_fps" | awk '{print ($1 > $2)}') )); then
        max_fps="$fps_decimal"
    fi

    total_fps=$(awk "BEGIN {printf \"%.3f\", $total_fps + $fps_decimal}")
    ((count++))

    echo ""
done

# Check if any files were processed
if [[ $count -eq 0 ]]; then
    echo "No valid WebM files could be processed."
    exit 0
fi

# Calculate average
average_fps=$(awk "BEGIN {printf \"%.3f\", $total_fps / $count}")

# Display results
echo "========================================"
echo "ANALYSIS RESULTS"
echo "========================================"
echo "Files processed: $count"
echo ""
echo "📈 STATISTICS:"
echo "  Minimum FPS: $min_fps"
echo "  Maximum FPS: $max_fps"
echo "  Average FPS: $average_fps"
echo ""
echo "📋 INDIVIDUAL FILE DETAILS:"
echo "----------------------------------------"

# Display individual file FPS
for i in "${!filenames[@]}"; do
    printf "%-40s | %s FPS\n" "${filenames[$i]}" "${fps_values[$i]}"
done

echo "----------------------------------------"
echo "Analysis complete! 🎬"
