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

SSL configuration handling for app factory.
"""

from typing import Dict, Any


def build_server_ssl_config(app_config: Dict[str, Any]) -> Dict[str, Any]:
    """
    Build SSL configuration for server from app_config.

    Args:
        app_config: Application configuration dictionary

    Returns:
        Dictionary with SSL configuration for server
    """
    ssl_config = {}

    # Check for SSL config in root ssl section first (new format)
    if app_config and "ssl" in app_config:
        root_ssl_config = app_config["ssl"]
        if root_ssl_config.get("enabled", False):
            ssl_config["certfile"] = root_ssl_config.get("cert_file")
            ssl_config["keyfile"] = root_ssl_config.get("key_file")
            ssl_config["ca_certs"] = root_ssl_config.get(
                "ca_cert_file", root_ssl_config.get("ca_cert")
            )
            # Set verify_mode based on verify_client setting
            if root_ssl_config.get("verify_client", False):
                ssl_config["verify_mode"] = "CERT_REQUIRED"
            else:
                ssl_config["verify_mode"] = root_ssl_config.get("verify_mode")
            print(f"🔒 SSL enabled: cert={root_ssl_config.get('cert_file')}, key={root_ssl_config.get('key_file')}")

    # Check for SSL config in security section (fallback)
    if app_config and "security" in app_config:
        security_config = app_config["security"]
        if "ssl" in security_config and security_config["ssl"].get("enabled", False):
            sec_ssl_config = security_config["ssl"]
            # Only use if not already set from root ssl section
            if "certfile" not in ssl_config:
                ssl_config["certfile"] = sec_ssl_config.get("cert_file")
                ssl_config["keyfile"] = sec_ssl_config.get("key_file")
                ssl_config["ca_certs"] = sec_ssl_config.get(
                    "ca_cert_file", sec_ssl_config.get("ca_cert")
                )
                ssl_config["verify_mode"] = sec_ssl_config.get("verify_mode")
                print(f"🔒 SSL enabled: cert={sec_ssl_config.get('cert_file')}, key={sec_ssl_config.get('key_file')}")

    return ssl_config


def is_mtls_enabled(app_config: Dict[str, Any]) -> bool:
    """
    Check if mTLS is enabled in configuration.

    Args:
        app_config: Application configuration dictionary

    Returns:
        True if mTLS is enabled, False otherwise
    """
    ssl_config = app_config.get("ssl", {}) if app_config else {}
    return ssl_config.get("verify_client", False)

