from __future__ import annotations

"""
Copyright (C) 2025 Luciano Guerche

This file is part of rabbitmq-mcp-server.

rabbitmq-mcp-server is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

rabbitmq-mcp-server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with rabbitmq-mcp-server. If not, see <https://www.gnu.org/licenses/>.
"""

"""TLS/SSL context management for AMQP connections."""

import ssl
from pathlib import Path

from rabbitmq_mcp_connection.logging.config import get_logger

logger = get_logger(__name__)


class TLSContextManager:
    """Manages SSL/TLS context generation for secure AMQP connections."""

    @staticmethod
    def create_ssl_context(
        *,
        verify_cert: bool = True,
        ca_bundle: str | None = None,
    ) -> ssl.SSLContext:
        """Create SSL context for AMQP connection.

        Args:
            verify_cert: Whether to verify server certificate (default: True)
            ca_bundle: Path to custom CA certificate bundle file (optional)

        Returns:
            Configured SSLContext for use with aio-pika connect_robust

        Raises:
            FileNotFoundError: If ca_bundle path is provided but doesn't exist
            ssl.SSLError: If SSL context creation fails
        """
        # Create context with secure TLS protocol
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)

        # Enforce minimum TLS version 1.2 (AC #1, #2)
        # Prefer TLS 1.3 when available for maximum security, fallback to 1.2
        try:
            context.minimum_version = ssl.TLSVersion.TLSv1_3
        except (AttributeError, ValueError):
            # Python < 3.10 or TLS 1.3 not available, use TLS 1.2
            context.minimum_version = ssl.TLSVersion.TLSv1_2

        # Configure certificate verification
        if verify_cert:
            context.check_hostname = True
            context.verify_mode = ssl.CERT_REQUIRED

            # Load custom CA bundle if provided
            if ca_bundle:
                ca_path = Path(ca_bundle)
                if not ca_path.exists():
                    raise FileNotFoundError(f"CA bundle not found: {ca_bundle}")
                context.load_verify_locations(cafile=str(ca_path))
                logger.info(
                    "tls.custom_ca_loaded",
                    ca_bundle=ca_bundle,
                )

            logger.info(
                "tls.context_created",
                message="Using TLS/SSL for connection (verify=True)",
                verify_cert=verify_cert,
                protocol=str(context.minimum_version),
            )
        else:
            # Disable verification (log security warning)
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
            logger.warning(
                "tls.verification_disabled",
                message="Certificate verification disabled - this is a security risk",
                security_warning=True,
            )
            logger.info(
                "tls.context_created",
                message="Using TLS/SSL for connection (verify=False)",
                verify_cert=verify_cert,
                protocol=str(context.minimum_version),
            )

        return context
