#!/usr/bin/env python3
"""
400대 에이전트 PC 대응 서버 시작 스크립트
운영 환경에서 Gunicorn 사용, 개발 환경에서 Flask 내장 서버 사용
"""

import os
import sys
import subprocess
import platform

def check_dependencies():
    """필요한 패키지 확인"""
    required_packages = ['gunicorn', 'gevent', 'psutil']
    missing = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing.append(package)
    
    return missing

def install_packages(packages):
    """패키지 자동 설치"""
    for package in packages:
        try:
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
            print(f"✅ {package} 설치 완료")
        except subprocess.CalledProcessError:
            print(f"❌ {package} 설치 실패")
            return False
    return True

def start_production_server():
    """운영 서버 시작 (Windows에서는 Waitress 사용)"""
    is_windows = platform.system() == 'Windows'
    
    if is_windows:
        print("🚀 Starting Production Server with Waitress (Windows)...")
        
        try:
            # Waitress 설치 확인
            import waitress
        except ImportError:
            print("📦 Waitress 설치 중...")
            try:
                subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'waitress'])
                import waitress
                print("✅ Waitress 설치 완료")
            except:
                print("❌ Waitress 설치 실패. 개발 서버로 실행합니다.")
                return start_development_server()
        
        try:
            # server.py import
            import server
            
            # Waitress로 서버 시작
            waitress.serve(
                server.app,
                host='0.0.0.0',
                port=8800,
                threads=20,  # 스레드 수 증가
                url_scheme='http',
                cleanup_interval=30,
                channel_timeout=120
            )
        except KeyboardInterrupt:
            print("\n⏹️ Server stopped by user")
            return True
        except Exception as e:
            print(f"❌ Waitress 시작 실패: {e}")
            return False
    else:
        print("🚀 Starting Production Server with Gunicorn...")
        
        # Gunicorn 명령어 구성
        cmd = [
            'gunicorn',
            '--config', 'gunicorn_config.py',
            'server:app'
        ]
        
        try:
            # 서버 시작
            subprocess.run(cmd, check=True)
        except subprocess.CalledProcessError as e:
            print(f"❌ Gunicorn 시작 실패: {e}")
            return False
        except KeyboardInterrupt:
            print("\n⏹️ Server stopped by user")
            return True
    
    return True

def start_development_server():
    """개발 서버 시작 (Flask 내장)"""
    print("🔧 Starting Development Server...")
    
    # 현재 스크립트 경로로 이동
    current_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(current_dir)
    
    # server.py 직접 실행
    try:
        import server
        # 기본 Flask 서버 실행 (개발용)
        server.app.run(host='0.0.0.0', port=8800, debug=False, threaded=True)
    except KeyboardInterrupt:
        print("\n⏹️ Server stopped by user")
        return True
    except Exception as e:
        print(f"❌ 서버 시작 실패: {e}")
        return False

def main():
    print("=" * 60)
    print("🏥 GeoMedical Asset Management Server")
    print("🎯 400대 동시 접속 대응 버전")
    print("=" * 60)
    
    # 운영체제 확인
    is_windows = platform.system() == 'Windows'
    
    # 모드 선택
    mode = input("\n서버 모드를 선택하세요:\n1. 운영 서버 (Gunicorn - 권장)\n2. 개발 서버 (Flask 내장)\n선택 (1-2): ").strip()
    
    if mode == '1':
        # 의존성 확인
        missing = check_dependencies()
        if missing:
            print(f"\n📦 누락된 패키지: {missing}")
            install_choice = input("자동으로 설치하시겠습니까? (y/n): ").strip().lower()
            
            if install_choice == 'y':
                if not install_packages(missing):
                    print("❌ 패키지 설치 실패. 개발 서버로 실행합니다.")
                    start_development_server()
                    return
            else:
                print("❌ 필요한 패키지가 없습니다. 개발 서버로 실행합니다.")
                start_development_server()
                return
        
        # Windows 환경 안내
        if is_windows:
            print("\n📋 Windows 환경에서 Waitress WSGI 서버를 사용합니다.")
            print("📋 400대 에이전트 동시 접속을 지원합니다.")
        
        start_production_server()
        
    elif mode == '2':
        start_development_server()
    else:
        print("❌ 잘못된 선택입니다.")

if __name__ == '__main__':
    main()