#!/bin/bash

# Website Color and Font Analyzer Runner Script
# Convenient wrapper script for the website analysis tool

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'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Function to print colored output
print_color() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

print_color $PURPLE "🎨 Website Color and Font Analyzer"
print_color $PURPLE "================================="
echo ""

# Check if script exists
if [[ ! -f "website_analyzer.py" ]]; then
    print_color $RED "❌ website_analyzer.py not found!"
    print_color $YELLOW "💡 Make sure you're in the website-analyzer directory"
    exit 1
fi

# Check if Python is available
if ! command -v python3 &> /dev/null; then
    print_color $RED "❌ Python 3 is not installed"
    print_color $YELLOW "💡 Please install Python 3.7+ first"
    exit 1
fi

# Function to show usage
show_usage() {
    print_color $CYAN "📖 Usage:"
    echo "  $0 [mode] [options]"
    echo ""
    print_color $CYAN "🔧 Modes:"
    echo "  analyze    - Complete website analysis (colors + fonts)"
    echo "  palette    - Extract color palette only"
    echo "  stats      - Show analysis statistics"
    echo "  test       - Run system tests"
    echo "  interactive - Interactive mode (guided prompts)"
    echo ""
    print_color $CYAN "📊 Examples:"
    echo "  $0 analyze https://stripe.com"
    echo "  $0 palette https://dribbble.com"
    echo "  $0 interactive"
    echo "  $0 stats"
    echo ""
}

# Function for interactive mode
interactive_mode() {
    print_color $BLUE "🤖 Interactive Website Analysis Mode"
    print_color $BLUE "===================================="
    echo ""
    
    # Ask for URL
    read -p "🌐 Enter website URL to analyze: " url
    
    if [[ -z "$url" ]]; then
        print_color $RED "❌ No URL provided"
        exit 1
    fi
    
    # Add protocol if missing
    if [[ ! "$url" =~ ^https?:// ]]; then
        url="https://$url"
        print_color $YELLOW "💡 Added https:// prefix: $url"
    fi
    
    # Ask for analysis type
    echo ""
    print_color $CYAN "🎯 Analysis Type:"
    echo "1. Complete analysis (colors + fonts + screenshots)"
    echo "2. Color palette only (faster)"
    echo "3. Font analysis focus"
    echo ""
    read -p "🤔 Choose analysis type (1-3): " analysis_type
    
    case $analysis_type in
        1)
            mode="analyze"
            print_color $GREEN "✅ Complete analysis selected"
            ;;
        2)
            mode="palette"
            print_color $GREEN "✅ Color palette analysis selected"
            ;;
        3)
            mode="analyze"
            font_focus="--font-focus"
            print_color $GREEN "✅ Font-focused analysis selected"
            ;;
        *)
            mode="analyze"
            print_color $YELLOW "⚠️  Default: Complete analysis"
            ;;
    esac
    
    # Ask for output directory
    echo ""
    read -p "📁 Output directory (default: website_analysis): " output_dir
    if [[ -z "$output_dir" ]]; then
        output_dir="website_analysis"
    fi
    
    # Ask for additional options
    echo ""
    print_color $CYAN "⚙️  Additional Options:"
    read -p "🖥️  Show browser window? (y/N): " show_browser
    read -p "📝 Verbose output? (y/N): " verbose
    read -p "🎨 Max colors to analyze (default: 20): " max_colors
    
    if [[ -z "$max_colors" ]]; then
        max_colors="20"
    fi
    
    # Build command
    cmd="python3 website_analyzer.py $mode \"$url\" -o \"$output_dir\" --max-colors $max_colors"
    
    if [[ "$show_browser" == "y" || "$show_browser" == "Y" ]]; then
        cmd="$cmd --no-headless"
    fi
    
    if [[ "$verbose" == "y" || "$verbose" == "Y" ]]; then
        cmd="$cmd -v"
    fi
    
    if [[ -n "$font_focus" ]]; then
        cmd="$cmd $font_focus"
    fi
    
    # Show summary
    echo ""
    print_color $PURPLE "📋 Analysis Summary:"
    print_color $CYAN "   URL: $url"
    print_color $CYAN "   Type: $mode"
    print_color $CYAN "   Output: $output_dir"
    print_color $CYAN "   Max Colors: $max_colors"
    print_color $CYAN "   Headless: $(if [[ "$show_browser" == "y" || "$show_browser" == "Y" ]]; then echo "No"; else echo "Yes"; fi)"
    print_color $CYAN "   Verbose: $(if [[ "$verbose" == "y" || "$verbose" == "Y" ]]; then echo "Yes"; else echo "No"; fi)"
    echo ""
    
    read -p "🚀 Proceed with analysis? (Y/n): " proceed
    if [[ "$proceed" == "n" || "$proceed" == "N" ]]; then
        print_color $YELLOW "❌ Analysis cancelled"
        exit 0
    fi
    
    print_color $GREEN "🚀 Starting analysis..."
    echo ""
    
    # Execute command
    eval $cmd
}

# Function to run quick analysis
quick_analyze() {
    local url=$1
    local mode=${2:-analyze}
    
    if [[ -z "$url" ]]; then
        print_color $RED "❌ No URL provided"
        show_usage
        exit 1
    fi
    
    # Add protocol if missing
    if [[ ! "$url" =~ ^https?:// ]]; then
        url="https://$url"
        print_color $YELLOW "💡 Added https:// prefix: $url"
    fi
    
    print_color $GREEN "🚀 Starting $mode analysis of: $url"
    echo ""
    
    python3 website_analyzer.py $mode "$url" "$@"
}

# Function to run tests
run_tests() {
    print_color $BLUE "🧪 Running Website Analyzer Tests"
    print_color $BLUE "================================="
    echo ""
    
    if [[ -f "test_analyzer.py" ]]; then
        python3 test_analyzer.py
    else
        print_color $YELLOW "⚠️  test_analyzer.py not found, running basic tests..."
        python3 website_analyzer.py stats
    fi
}

# Function to show analysis statistics
show_stats() {
    print_color $BLUE "📊 Website Analysis Statistics"
    print_color $BLUE "=============================="
    echo ""
    
    python3 website_analyzer.py stats
}

# Function to batch analyze multiple URLs
batch_analyze() {
    local file=$1
    
    if [[ ! -f "$file" ]]; then
        print_color $RED "❌ File not found: $file"
        exit 1
    fi
    
    print_color $BLUE "📦 Batch Analysis Mode"
    print_color $BLUE "======================"
    echo ""
    
    local count=0
    local success=0
    
    while IFS= read -r url; do
        # Skip empty lines and comments
        if [[ -z "$url" || "$url" =~ ^# ]]; then
            continue
        fi
        
        count=$((count + 1))
        print_color $CYAN "🔄 [$count] Analyzing: $url"
        
        if python3 website_analyzer.py analyze "$url" -o "batch_analysis_$(date +%Y%m%d_%H%M%S)"; then
            success=$((success + 1))
            print_color $GREEN "✅ [$count] Success: $url"
        else
            print_color $RED "❌ [$count] Failed: $url"
        fi
        
        echo ""
        
        # Add delay between requests to be respectful
        sleep 2
        
    done < "$file"
    
    echo ""
    print_color $PURPLE "📈 Batch Analysis Complete:"
    print_color $CYAN "   Total URLs: $count"
    print_color $CYAN "   Successful: $success"
    print_color $CYAN "   Failed: $((count - success))"
    print_color $CYAN "   Success Rate: $(echo "scale=1; $success * 100 / $count" | bc -l)%"
}

# Function to compare websites
compare_websites() {
    print_color $BLUE "🔄 Website Comparison Mode"
    print_color $BLUE "========================="
    echo ""
    
    read -p "🌐 Enter first website URL: " url1
    read -p "🌐 Enter second website URL: " url2
    
    if [[ -z "$url1" || -z "$url2" ]]; then
        print_color $RED "❌ Both URLs are required"
        exit 1
    fi
    
    # Add protocols if missing
    if [[ ! "$url1" =~ ^https?:// ]]; then
        url1="https://$url1"
    fi
    if [[ ! "$url2" =~ ^https?:// ]]; then
        url2="https://$url2"
    fi
    
    timestamp=$(date +%Y%m%d_%H%M%S)
    
    print_color $GREEN "🚀 Analyzing first website: $url1"
    python3 website_analyzer.py analyze "$url1" -o "comparison_${timestamp}_site1"
    
    echo ""
    print_color $GREEN "🚀 Analyzing second website: $url2"
    python3 website_analyzer.py analyze "$url2" -o "comparison_${timestamp}_site2"
    
    echo ""
    print_color $PURPLE "📊 Comparison complete! Check directories:"
    print_color $CYAN "   Site 1: comparison_${timestamp}_site1/"
    print_color $CYAN "   Site 2: comparison_${timestamp}_site2/"
}

# Function to analyze trending design sites
analyze_trending() {
    print_color $BLUE "🔥 Trending Design Sites Analysis"
    print_color $BLUE "================================="
    echo ""
    
    local sites=(
        "https://dribbble.com"
        "https://www.awwwards.com"
        "https://www.behance.net"
        "https://stripe.com"
        "https://www.figma.com"
    )
    
    print_color $CYAN "📋 Will analyze these trending design sites:"
    for site in "${sites[@]}"; do
        echo "   • $site"
    done
    echo ""
    
    read -p "🚀 Proceed with trending sites analysis? (Y/n): " proceed
    if [[ "$proceed" == "n" || "$proceed" == "N" ]]; then
        print_color $YELLOW "❌ Analysis cancelled"
        exit 0
    fi
    
    timestamp=$(date +%Y%m%d_%H%M%S)
    
    for i in "${!sites[@]}"; do
        local site="${sites[$i]}"
        local num=$((i + 1))
        
        print_color $GREEN "🚀 [$num/${#sites[@]}] Analyzing: $site"
        python3 website_analyzer.py analyze "$site" -o "trending_${timestamp}_site${num}"
        
        echo ""
        sleep 3  # Be respectful with delays
    done
    
    print_color $PURPLE "🎉 Trending design analysis complete!"
    print_color $CYAN "📁 Check directories: trending_${timestamp}_site*/"
}

# Main script logic
case "${1:-interactive}" in
    "analyze")
        shift
        quick_analyze "$@"
        ;;
    "palette")
        shift
        quick_analyze "$1" "palette" "${@:2}"
        ;;
    "stats")
        show_stats
        ;;
    "test")
        run_tests
        ;;
    "interactive" | "")
        interactive_mode
        ;;
    "batch")
        if [[ -z "$2" ]]; then
            print_color $RED "❌ Usage: $0 batch <file_with_urls>"
            exit 1
        fi
        batch_analyze "$2"
        ;;
    "compare")
        compare_websites
        ;;
    "trending")
        analyze_trending
        ;;
    "help" | "-h" | "--help")
        show_usage
        ;;
    *)
        # Assume it's a URL if it doesn't match known commands
        if [[ "$1" =~ ^https?:// ]] || [[ "$1" =~ \. ]]; then
            quick_analyze "$@"
        else
            print_color $RED "❌ Unknown command: $1"
            echo ""
            show_usage
            exit 1
        fi
        ;;
esac

# Check if analysis was successful and show next steps
if [[ $? -eq 0 && "$1" != "stats" && "$1" != "test" && "$1" != "help" ]]; then
    echo ""
    print_color $GREEN "🎉 Analysis completed successfully!"
    echo ""
    print_color $CYAN "📋 Next steps:"
    echo "   • Check the output directory for results"
    echo "   • View screenshots and color swatches"
    echo "   • Read the JSON analysis report"
    echo "   • Use extracted colors and fonts in your designs"
    echo ""
    print_color $YELLOW "💡 Tips:"
    echo "   • Run 'python3 website_analyzer.py stats' to see all analyses"
    echo "   • Use batch mode to analyze multiple sites"
    echo "   • Compare different websites using compare mode"
    echo ""
fi 