#!/usr/bin/env python3
"""
Startup script for the Karaoke Duplicate Review Web UI
"""

import os
import sys
import subprocess
import webbrowser
from time import sleep

def check_dependencies():
    """Check if required dependencies are installed."""
    dependencies_ok = True
    
    # Check Flask
    try:
        import flask
        print("✅ Flask is installed")
    except ImportError:
        print("❌ Flask is not installed")
        print("Installing Flask...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "flask>=2.0.0"])
            print("✅ Flask installed successfully")
        except subprocess.CalledProcessError:
            print("❌ Failed to install Flask")
            dependencies_ok = False
    
    # Check fuzzywuzzy for playlist validation
    try:
        import fuzzywuzzy
        print("✅ fuzzywuzzy is installed (for playlist validation)")
    except ImportError:
        print("❌ fuzzywuzzy is not installed")
        print("Installing fuzzywuzzy and python-Levenshtein...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "fuzzywuzzy>=0.18.0", "python-Levenshtein>=0.21.0"])
            print("✅ fuzzywuzzy installed successfully")
        except subprocess.CalledProcessError:
            print("❌ Failed to install fuzzywuzzy")
            print("⚠️  Playlist validation will work without fuzzy matching")
    
    return dependencies_ok

def check_data_files():
    """Check if required data files exist."""
    required_files = [
        "data/skipSongs.json",
        "config/config.json"
    ]
    
    # Check for detailed data file (preferred)
    detailed_file = "data/reports/skip_songs_detailed.json"
    if os.path.exists(detailed_file):
        print("✅ Found detailed skip data (recommended)")
    else:
        print("⚠️  Detailed skip data not found - using basic skip list")
    
    missing_files = []
    for file_path in required_files:
        if not os.path.exists(file_path):
            missing_files.append(file_path)
    
    if missing_files:
        print("❌ Missing required data files:")
        for file_path in missing_files:
            print(f"   - {file_path}")
        print("\nPlease run the CLI tool first to generate the skip list:")
        print("   python cli/main.py --save-reports")
        return False
    
    print("✅ All required data files found")
    return True

def start_web_ui():
    """Start the Flask web application."""
    print("\n🚀 Starting Karaoke Duplicate Review Web UI...")
    print("=" * 60)
    
    # Change to web directory
    web_dir = os.path.join(os.path.dirname(__file__), "web")
    if not os.path.exists(web_dir):
        print(f"❌ Web directory not found: {web_dir}")
        return False
    
    os.chdir(web_dir)
    
    # Start Flask app
    try:
        print("🌐 Web UI will be available at: http://localhost:5000")
        print("📱 You can open this URL in your web browser")
        print("\n⏳ Starting server... (Press Ctrl+C to stop)")
        print("-" * 60)
        
        # Open browser after a short delay
        def open_browser():
            sleep(2)
            webbrowser.open("http://localhost:5000")
        
        import threading
        browser_thread = threading.Thread(target=open_browser)
        browser_thread.daemon = True
        browser_thread.start()
        
        # Start Flask app
        subprocess.run([sys.executable, "app.py"])
        
    except KeyboardInterrupt:
        print("\n\n🛑 Web UI stopped by user")
    except Exception as e:
        print(f"\n❌ Error starting web UI: {e}")
        return False
    
    return True

def main():
    """Main function."""
    print("🎤 Karaoke Duplicate Review Web UI")
    print("=" * 40)
    
    # Check dependencies
    if not check_dependencies():
        return False
    
    # Check data files
    if not check_data_files():
        return False
    
    # Start web UI
    return start_web_ui()

if __name__ == "__main__":
    success = main()
    if not success:
        sys.exit(1) 