"""
Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

SSL context handler for UniversalClient.
"""

import os
import ssl
from typing import Dict, Optional

try:
    from mcp_security_framework import SecurityManager

    SECURITY_FRAMEWORK_AVAILABLE = True
except ImportError:
    SECURITY_FRAMEWORK_AVAILABLE = False
    SecurityManager = None


class SSLHandler:
    """Handler for SSL context creation."""

    def __init__(self, security_config: Dict, security_manager=None):
        """
        Initialize SSL handler.
        
        Args:
            security_config: Security configuration dictionary
            security_manager: Optional security manager instance
        """
        self.security_config = security_config
        self.security_manager = security_manager

    def create_ssl_context(self) -> Optional[ssl.SSLContext]:
        """
        Create SSL context for secure connections.
        
        Returns:
            SSL context or None if SSL is not enabled
        """
        ssl_config = self.security_config.get("ssl", {})
        if not ssl_config.get("enabled", False):
            return None

        try:
            context: Optional[ssl.SSLContext] = None

            # Try security framework first
            if self.security_manager:
                try:
                    context = self.security_manager.create_client_ssl_context()
                except Exception:
                    context = None

            # Fallback SSL context creation
            if context is None:
                context = ssl.create_default_context()

            # Always honor explicit client certificate config for mTLS
            cert_config = self.security_config.get("certificate", {})
            if cert_config.get("enabled", False):
                cert_file = cert_config.get("cert_file")
                key_file = cert_config.get("key_file")
                if cert_file and key_file:
                    context.load_cert_chain(certfile=cert_file, keyfile=key_file)

            # Add CA certificate if provided
            ca_cert_file = ssl_config.get("ca_cert_file") or ssl_config.get(
                "ca_cert"
            )
            if ca_cert_file and os.path.exists(ca_cert_file):
                context.load_verify_locations(cafile=ca_cert_file)

            # Configure verification
            if ssl_config.get("check_hostname", True):
                context.check_hostname = True
                context.verify_mode = ssl.CERT_REQUIRED
            else:
                context.check_hostname = False
                context.verify_mode = ssl.CERT_NONE

            return context
        except Exception as e:
            print(f"Warning: Failed to create SSL context: {e}")
            return None

