#!/usr/bin/env python3
"""
Startup script for KPI Analysis Dashboard
Provides easy way to run the application with proper configuration
"""

import os
import sys
import argparse
from pathlib import Path

# Add current directory to Python path
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

def check_dependencies():
    """Check if required dependencies are installed"""
    required_packages = [
        'fastapi', 'uvicorn', 'pandas', 'openpyxl', 
        'plotly', 'matplotlib', 'reportlab', 'openai'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ Missing required packages:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n💡 Install missing packages with:")
        print(f"   pip install {' '.join(missing_packages)}")
        return False
    
    print("✅ All required packages are installed")
    return True

def check_environment():
    """Check environment configuration"""
    env_file = current_dir / ".env"
    
    if not env_file.exists():
        print("⚠️  No .env file found")
        print("📝 Creating .env file from template...")
        
        template_file = current_dir / "config" / ".env.template"
        if template_file.exists():
            import shutil
            shutil.copy(template_file, env_file)
            print("✅ .env file created from template")
            print("📝 Please edit .env file with your configuration")
        else:
            print("❌ .env.template file not found")
            return False
    else:
        print("✅ .env file found")
    
    # Check critical directories
    directories = ['data', 'uploads', 'reports', 'logs']
    for directory in directories:
        dir_path = current_dir / directory
        dir_path.mkdir(exist_ok=True)
    
    print("✅ Required directories created")
    return True

def setup_database():
    """Setup database tables"""
    try:
        from app.core.database import init_db
        
        print("🗄️  Setting up database...")
        import asyncio
        
        async def setup():
            await init_db()
            print("✅ Database initialized successfully")
        
        asyncio.run(setup())
        return True
        
    except Exception as e:
        print(f"❌ Database setup failed: {e}")
        return False

def run_development():
    """Run application in development mode"""
    print("🚀 Starting KPI Analysis Dashboard in development mode...")
    print("📊 Dashboard: http://localhost:8000")
    print("📚 API Docs: http://localhost:8000/docs")
    print("⚡ Auto-reload enabled")
    print("-" * 50)
    
    try:
        import uvicorn
        uvicorn.run(
            "main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_level="info",
            access_log=True
        )
    except KeyboardInterrupt:
        print("\n👋 Application stopped by user")
    except Exception as e:
        print(f"❌ Error starting application: {e}")

def run_production():
    """Run application in production mode"""
    print("🚀 Starting KPI Analysis Dashboard in production mode...")
    print("📊 Dashboard: http://localhost:8000")
    print("-" * 50)
    
    try:
        import uvicorn
        uvicorn.run(
            "main:app",
            host="0.0.0.0",
            port=8000,
            workers=4,
            log_level="info",
            access_log=False
        )
    except KeyboardInterrupt:
        print("\n👋 Application stopped by user")
    except Exception as e:
        print(f"❌ Error starting application: {e}")

def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(description="KPI Analysis Dashboard")
    parser.add_argument(
        '--mode', 
        choices=['dev', 'production'], 
        default='dev',
        help='Run mode (default: dev)'
    )
    parser.add_argument(
        '--check', 
        action='store_true',
        help='Check system requirements only'
    )
    parser.add_argument(
        '--setup', 
        action='store_true',
        help='Setup database and environment only'
    )
    
    args = parser.parse_args()
    
    print("🎯 KPI Analysis Dashboard Setup")
    print("=" * 40)
    
    # Check dependencies
    if not check_dependencies():
        return 1
    
    # Check environment
    if not check_environment():
        return 1
    
    # Setup database if requested
    if args.setup:
        setup_database()
        return 0
    
    # Check mode only
    if args.check:
        print("✅ System check completed successfully")
        return 0
    
    # Setup database
    if not setup_database():
        return 1
    
    print("\n🎉 Setup completed! Starting application...")
    
    # Run application
    if args.mode == 'production':
        run_production()
    else:
        run_development()
    
    return 0

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