#!/usr/bin/env python3
"""
Startup script for Smart Farm Photo Keyword Tagging AI Web UI
"""

import os
import sys
import subprocess
import time
import webbrowser
from pathlib import Path

def check_dependencies():
    """Check if required dependencies are installed"""
    print("🔍 Checking dependencies...")
    
    required_packages = ['fastapi', 'uvicorn', 'python-multipart']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
            print(f"  ✅ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"  ❌ {package}")
    
    if missing_packages:
        print(f"\n📦 Installing missing packages: {', '.join(missing_packages)}")
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install"
            ] + missing_packages)
            print("✅ Dependencies installed successfully!")
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to install dependencies: {e}")
            return False
    
    return True

def start_server():
    """Start the FastAPI server"""
    print("\n🚀 Starting Smart Farm AI Web UI...")
    print("=" * 50)
    
    # Change to project directory
    project_dir = Path(__file__).parent
    os.chdir(project_dir)
    
    # Start the server
    try:
        import uvicorn
        
        print("🌐 Server starting at: http://localhost:8000")
        print("📚 API Documentation: http://localhost:8000/docs")
        print("📋 Alternative Docs: http://localhost:8000/redoc")
        print("\n⏹️  Press Ctrl+C to stop the server")
        print("=" * 50)
        
        # Open browser after a short delay
        def open_browser():
            time.sleep(2)
            try:
                webbrowser.open("http://localhost:8000")
                print("🌐 Opened web browser automatically")
            except:
                print("🌐 Please open http://localhost:8000 in your browser")
        
        import threading
        browser_thread = threading.Thread(target=open_browser)
        browser_thread.daemon = True
        browser_thread.start()
        
        # Start the server
        uvicorn.run(
            "src.api.main:app",
            host="0.0.0.0",
            port=8000,
            reload=False,
            log_level="info"
        )
        
    except KeyboardInterrupt:
        print("\n\n🛑 Server stopped by user")
    except Exception as e:
        print(f"\n❌ Error starting server: {e}")
        print("\nTroubleshooting:")
        print("1. Make sure you're in the project directory")
        print("2. Check that all dependencies are installed: pip install -r requirements.txt")
        print("3. Verify Python version is 3.8+")

def main():
    """Main function"""
    print("🚜 Smart Farm Photo Keyword Tagging AI")
    print("🌐 Professional Web Interface")
    print("=" * 50)
    
    # Check dependencies
    if not check_dependencies():
        print("\n❌ Dependency check failed. Please install requirements manually:")
        print("pip install fastapi uvicorn python-multipart")
        return
    
    # Start server
    start_server()

if __name__ == "__main__":
    main()
