#!/usr/bin/env python3
"""
Production runner for Sharey using Gunicorn
"""
import sys
import os
import subprocess
from pathlib import Path

def check_gunicorn():
    """Check if gunicorn is installed"""
    try:
        import gunicorn
        return True
    except ImportError:
        return False

def install_gunicorn():
    """Install gunicorn"""
    print("📦 Installing gunicorn...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "gunicorn"])
        print("✅ Gunicorn installed successfully")
        return True
    except subprocess.CalledProcessError:
        print("❌ Failed to install gunicorn")
        return False

def start_production_server():
    """Start Sharey with Gunicorn"""
    
    # Add src directory to Python path
    src_path = Path(__file__).parent / "src"
    if str(src_path) not in sys.path:
        sys.path.insert(0, str(src_path))
    
    # Check if gunicorn is available
    if not check_gunicorn():
        print("⚠️  Gunicorn not found")
        if input("📦 Install gunicorn? (y/n): ").lower().startswith('y'):
            if not install_gunicorn():
                return False
        else:
            print("❌ Cannot start production server without gunicorn")
            return False
    
    print("🚀 Starting Sharey with Gunicorn (Production Mode)")
    print("=" * 60)
    
    # Load configuration
    try:
        from config import config
        host = config.get('flask.host', '0.0.0.0')
        port = config.get('flask.port', 8866)
        
        print(f"🌐 Host: {host}")
        print(f"🔌 Port: {port}")
        print(f"📁 Working directory: {Path.cwd()}")
        print("=" * 60)
        
    except Exception as e:
        print(f"❌ Error loading configuration: {e}")
        return False
    
    # Gunicorn command arguments
    gunicorn_args = [
        sys.executable, "-m", "gunicorn",
        "--bind", f"{host}:{port}",
        "--workers", "4",
        "--worker-class", "sync",
        "--timeout", "120",
        "--max-requests", "1000",
        "--max-requests-jitter", "100",
        "--access-logfile", "-",
        "--error-logfile", "-",
        "--log-level", "info",
        "--pythonpath", str(src_path),
        "wsgi:app"
    ]
    
    try:
        print("🎯 Starting server...")
        print("Press Ctrl+C to stop")
        print("=" * 60)
        subprocess.run(gunicorn_args)
        
    except KeyboardInterrupt:
        print("\n👋 Server stopped by user")
    except Exception as e:
        print(f"❌ Error starting server: {e}")
        return False
    
    return True

def main():
    """Main entry point"""
    print("🏭 Sharey Production Server")
    print("=" * 40)
    
    if start_production_server():
        print("✅ Server stopped gracefully")
    else:
        print("❌ Server failed to start")
        sys.exit(1)

if __name__ == "__main__":
    main()
