#!/bin/bash
# Enhanced music downloader script for Warp Workflow
# Downloads music with album art, lyrics, and comprehensive metadata
# Uses virtual environment with enhanced dependencies

set -euo pipefail

# Detect the script's location and project directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
VENV_PYTHON="$PROJECT_DIR/.venv/bin/python3"
LYRICS_SCRIPT="$PROJECT_DIR/scripts/lyrics_metadata.py"

# Check if virtual environment and dependencies are available
check_dependencies() {
    if [[ ! -f "$VENV_PYTHON" ]]; then
        echo "⚠️  Virtual environment not found at $PROJECT_DIR/.venv"
        echo "   Run: cd $PROJECT_DIR && python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt"
        return 1
    fi
    
    # Test core dependencies
    if ! "$VENV_PYTHON" -c "import eyed3, requests" 2>/dev/null; then
        echo "⚠️  Missing required dependencies in virtual environment"
        echo "   Run: cd $PROJECT_DIR && source .venv/bin/activate && pip install -r requirements.txt"
        return 1
    fi
    
    return 0
}

# Initialize virtual environment check
if check_dependencies; then
    echo "✅ Enhanced metadata features available"
    USE_ENHANCED=true
    INSTANTMUSIC_CMD="$HOME/.local/bin/instantmusic"  # Use the working version
else
    echo "⚠️  Using basic functionality only - enhanced features disabled"
    USE_ENHANCED=false
    VENV_PYTHON="python3"  # Fallback to system Python
    INSTANTMUSIC_CMD="instantmusic"  # Use system version
fi

# Function to display usage
show_usage() {
    echo "🎵 Music Downloader with Album Art Organization"
    echo "Usage: download_music <artist> <song>"
    echo "   or: download_music '<artist> <song>'"
    echo ""
    echo "Examples:"
    echo "  download_music The Beatles Hey Jude"
    echo "  download_music 'Pink Floyd Comfortably Numb'"
    echo "  download_music Queen 'Bohemian Rhapsody'"
    echo ""
    echo "Files will be organized as: ~/Music/<Artist>/<Song>.mp3"
}

# Check arguments
if [ $# -eq 0 ] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
    show_usage
    exit 0
fi

# Handle different argument formats
if [ $# -eq 1 ]; then
    # Single argument - treat as full search term
    search_term="$1"
else
    # Multiple arguments - join them
    search_term="$*"
fi

# Create Music directory if it doesn't exist
mkdir -p "$HOME/Music"

echo "🔍 Searching for: $search_term"
echo "📁 Music will be organized in: ~/Music/<Artist>/<Song>.mp3"
echo "🎨 Album artwork will be automatically added using improved processor"
echo ""

# Store the original directory
original_dir=$(pwd)

# Find all MP3 files before download
echo "📊 Scanning existing MP3 files..."
before_files=()
while IFS= read -r -d '' file; do
    before_files+=("$file")
done < <(find "$HOME/Music" -name "*.mp3" -print0 2>/dev/null || true)

# Run instantmusic with the search term (disable built-in album art to avoid errors)
echo "🎵 Downloading audio..."
"$INSTANTMUSIC_CMD" -q -s "$search_term"

# Find new MP3 files after download
echo "🔍 Finding newly downloaded files..."
after_files=()
while IFS= read -r -d '' file; do
    after_files+=("$file")
done < <(find "$HOME/Music" -name "*.mp3" -print0 2>/dev/null || true)

# Determine new files
new_files=()
for file in "${after_files[@]}"; do
    found=false
    for old_file in "${before_files[@]}"; do
        if [[ "$file" == "$old_file" ]]; then
            found=true
            break
        fi
    done
    if [[ "$found" == false ]]; then
        new_files+=("$file")
    fi
done

# Process album art, lyrics, and metadata for new files
if [ ${#new_files[@]} -gt 0 ]; then
    echo "🎨 Processing album art, lyrics, and metadata for ${#new_files[@]} new file(s)..."
    
    # Extract artist and track from search term for better matching
    artist=""
    track=""
    # Try to parse "Artist Name Song Title" format - look for common patterns
    if [[ "$search_term" =~ ^([A-Z][a-z]+[[:space:]]+[A-Z][a-z]+)[[:space:]]+(.+)$ ]]; then
        # Match two-word artist names like "Ed Sheeran", "Taylor Swift", etc.
        artist="${BASH_REMATCH[1]}"
        track="${BASH_REMATCH[2]}"
        echo "🎯 Parsed: Artist='$artist', Track='$track'"
    elif [[ "$search_term" =~ ^([^[:space:]]+)[[:space:]]+(.+)$ ]]; then
        # Fallback to single-word artist
        artist="${BASH_REMATCH[1]}"
        track="${BASH_REMATCH[2]}"
        echo "🎯 Parsed: Artist='$artist', Track='$track'"
    fi
    
    for file in "${new_files[@]}"; do
        echo "🎵 Processing: $(basename "$file")"
        
        # Step 1: Add album art
        echo "🖼️  Adding album art..."
        if [[ -n "$artist" && -n "$track" ]]; then
            if fixalbumart_improved "$file" "$artist" "$track"; then
                echo "✅ Album art added successfully!"
            else
                echo "🔄 Trying auto-detection from filename..."
                if fixalbumart_improved "$file"; then
                    echo "✅ Album art added successfully!"
                else
                    echo "⚠️  Album art processing failed"
                fi
            fi
        else
            echo "🔄 Trying auto-detection from filename..."
            if fixalbumart_improved "$file"; then
                echo "✅ Album art added successfully!"
            else
                echo "⚠️  Album art processing failed"
            fi
        fi
        
        # Step 2: Add lyrics and comprehensive metadata
        if [[ "$USE_ENHANCED" == true ]]; then
            echo "📝 Adding lyrics and metadata..."
            if [[ -f "$LYRICS_SCRIPT" ]]; then
                if [[ -n "$artist" && -n "$track" ]]; then
                    if "$VENV_PYTHON" "$LYRICS_SCRIPT" "$file" --artist "$artist" --title "$track" 2>/dev/null; then
                        echo "✅ Lyrics and metadata added successfully!"
                    else
                        echo "⚠️  Lyrics/metadata processing failed (not critical)"
                    fi
                else
                    if "$VENV_PYTHON" "$LYRICS_SCRIPT" "$file" 2>/dev/null; then
                        echo "✅ Lyrics and metadata added successfully!"
                    else
                        echo "⚠️  Lyrics/metadata processing failed (not critical)"
                    fi
                fi
            else
                echo "⚠️  Lyrics/metadata script not found at: $LYRICS_SCRIPT"
            fi
        else
            echo "ℹ️  Enhanced metadata features disabled - skipping lyrics"
        fi
        
        echo "" # Add spacing between files
    done
else
    echo "ℹ️  No new files detected - file may already exist"
fi

echo ""
echo "✅ Download completed!"
echo "📂 Check ~/Music for your organized music collection"

