#!/bin/bash

# Audio Conversion Script for ZenTap
# Converts audio files according to specifications in assets/audio/README.md

set -e  # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Directories
AUDIO_DIR="assets/audio"
SOURCE_DIR="assets/audio/source"
OUTPUT_DIR="assets/audio"

echo -e "${BLUE}ZenTap Audio Conversion Script${NC}"
echo "=================================="

# Check if ffmpeg is installed
if ! command -v ffmpeg &> /dev/null; then
    echo -e "${RED}Error: ffmpeg is not installed${NC}"
    echo "Please install ffmpeg:"
    echo "  Ubuntu/Debian: sudo apt install ffmpeg"
    echo "  macOS: brew install ffmpeg"
    echo "  Windows: Download from https://ffmpeg.org/download.html"
    exit 1
fi

# Create directories if they don't exist
mkdir -p "$SOURCE_DIR"
mkdir -p "$OUTPUT_DIR"

echo -e "${YELLOW}Audio Conversion Specifications:${NC}"
echo "- Sound Effects: WAV format, 44.1 kHz, 16-bit, 0.1-0.5 seconds"
echo "- Background Music: MP3 format, 44.1 kHz, 128-320 kbps, 2-5 minutes"
echo ""

# Function to convert sound effects to WAV
convert_sound_effect() {
    local input_file="$1"
    local output_file="$2"
    
    echo -e "${BLUE}Converting sound effect: $(basename "$input_file")${NC}"
    
    ffmpeg -i "$input_file" \
        -ar 44100 \
        -sample_fmt s16 \
        -ac 1 \
        -t 0.5 \
        -y \
        "$output_file"
        
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Successfully converted $(basename "$output_file")${NC}"
    else
        echo -e "${RED}✗ Failed to convert $(basename "$input_file")${NC}"
    fi
}

# Function to convert background music to MP3
convert_background_music() {
    local input_file="$1"
    local output_file="$2"
    
    echo -e "${BLUE}Converting background music: $(basename "$input_file")${NC}"
    
    ffmpeg -i "$input_file" \
        -ar 44100 \
        -b:a 192k \
        -ac 2 \
        -y \
        "$output_file"
        
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Successfully converted $(basename "$output_file")${NC}"
    else
        echo -e "${RED}✗ Failed to convert $(basename "$input_file")${NC}"
    fi
}

# Function to validate audio file duration
validate_duration() {
    local file="$1"
    local expected_min="$2"
    local expected_max="$3"
    
    duration=$(ffprobe -v quiet -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file" 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$duration" ]; then
        # Convert to integer using awk for better compatibility
        duration_int=$(echo "$duration" | awk '{print int($1)}')
        if [ "$duration_int" -ge "$expected_min" ] && [ "$duration_int" -le "$expected_max" ]; then
            echo -e "${GREEN}✓ Duration validation passed: ${duration}s${NC}"
        else
            echo -e "${YELLOW}⚠ Duration warning: ${duration}s (expected ${expected_min}-${expected_max}s)${NC}"
        fi
    else
        echo -e "${YELLOW}⚠ Could not validate duration${NC}"
    fi
}

echo -e "${YELLOW}Looking for source files in $SOURCE_DIR${NC}"
echo ""

# Convert sound effects
for sound_effect in "bubble_pop" "bubble_pop_alt"; do
    # Look for various input formats
    for ext in wav mp3 ogg flac m4a; do
        source_file="$SOURCE_DIR/${sound_effect}.$ext"
        if [ -f "$source_file" ]; then
            output_file="$OUTPUT_DIR/${sound_effect}.wav"
            convert_sound_effect "$source_file" "$output_file"
            
            if [ -f "$output_file" ]; then
                validate_duration "$output_file" 0 1
            fi
            echo ""
            break
        fi
    done
done

# Convert background music
for music_track in "ambient_background" "zen_mode_background"; do
    # Look for various input formats
    for ext in wav mp3 ogg flac m4a; do
        source_file="$SOURCE_DIR/${music_track}.$ext"
        if [ -f "$source_file" ]; then
            output_file="$OUTPUT_DIR/${music_track}.mp3"
            convert_background_music "$source_file" "$output_file"
            
            if [ -f "$output_file" ]; then
                validate_duration "$output_file" 120 300  # 2-5 minutes
            fi
            echo ""
            break
        fi
    done
done

# Check if we have any missing files
echo -e "${YELLOW}Checking for required audio files:${NC}"

required_files=(
    "bubble_pop.wav"
    "bubble_pop_alt.wav"
    "ambient_background.mp3"
    "zen_mode_background.mp3"
)

missing_files=()
for file in "${required_files[@]}"; do
    if [ -f "$OUTPUT_DIR/$file" ]; then
        echo -e "${GREEN}✓ $file${NC}"
    else
        echo -e "${RED}✗ $file (missing)${NC}"
        missing_files+=("$file")
    fi
done

echo ""

if [ ${#missing_files[@]} -eq 0 ]; then
    echo -e "${GREEN}All required audio files are present!${NC}"
else
    echo -e "${YELLOW}Missing files: ${missing_files[*]}${NC}"
    echo ""
    echo -e "${BLUE}To add missing files:${NC}"
    echo "1. Place source audio files in $SOURCE_DIR/"
    echo "2. Run this script again"
    echo ""
    echo -e "${BLUE}Supported source formats:${NC} WAV, MP3, OGG, FLAC, M4A"
fi

echo ""
echo -e "${BLUE}Audio conversion complete!${NC}"