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

Lifespan management utilities for MCP Proxy Adapter API.
"""

import asyncio
import signal
from contextlib import asynccontextmanager
from typing import Any, Dict, Optional

from fastapi import FastAPI

from mcp_proxy_adapter.core.logging import get_global_logger
from .registration_manager import RegistrationManager, set_stop_flag_sync


class LifespanManager:
    """Manager for application lifespan events."""

    def __init__(self):
        """Initialize lifespan manager."""
        self.logger = get_global_logger()
        self.registration_manager = RegistrationManager()

    def create_lifespan(self, config_path: Optional[str] = None, current_config: Optional[Dict[str, Any]] = None):
        """
        Create lifespan manager for the FastAPI application.

        Args:
            config_path: Path to configuration file (optional)
            current_config: Current configuration data (optional)

        Returns:
            Lifespan context manager
        """

        def signal_handler(signum, frame):  # type: ignore[no-redef]
            """Handle interrupt signals (SIGINT, SIGTERM) by setting stop flag."""
            logger = get_global_logger()
            logger.info(f"🛑 Received signal {signum}, setting stop flag...")
            set_stop_flag_sync(True)
        
        # Register signal handlers for graceful shutdown
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        @asynccontextmanager
        async def lifespan(app: FastAPI):
            """Lifespan context manager."""
            # Startup
            logger = get_global_logger()
            try:
                logger.info("=" * 80)
                logger.info("🚀 LIFESPAN STARTUP CALLED")
                logger.info("=" * 80)
                logger.info("Starting MCP Proxy Adapter")
                logger.info(f"🔍 lifespan function: current_config parameter value: {current_config}")
                logger.info(f"🔍 lifespan function: current_config is None: {current_config is None}")
                
                # Start heartbeat task only if registration is enabled
                # Check if registration is enabled before calling start_heartbeat
                logger = get_global_logger()
                logger.info(f"🔍 Lifespan: current_config is {'None' if current_config is None else 'not None'}")
                if current_config:
                    logger.info(f"🔍 Lifespan: current_config type: {type(current_config)}")
                    logger.info(f"🔍 Lifespan: current_config keys: {list(current_config.keys()) if hasattr(current_config, 'keys') else 'no keys'}")
                    if hasattr(current_config, 'keys'):
                        logger.info(f"🔍 Lifespan: current_config['registration'] exists: {'registration' in current_config}")
                        if 'registration' in current_config:
                            reg_section = current_config.get('registration')
                            logger.info(f"🔍 Lifespan: registration section type: {type(reg_section)}")
                            logger.info(f"🔍 Lifespan: registration section: {reg_section}")
                    
                    registration_enabled = False
                    # Check SimpleConfigModel first
                    try:
                        from mcp_proxy_adapter.config import get_config
                        cfg = get_config()
                        logger.info(f"🔍 SimpleConfigModel: cfg type: {type(cfg)}")
                        logger.info(f"🔍 SimpleConfigModel: hasattr(cfg, 'model'): {hasattr(cfg, 'model')}")
                        if hasattr(cfg, "model"):
                            logger.info(f"🔍 SimpleConfigModel: cfg.model type: {type(cfg.model)}")
                            logger.info(f"🔍 SimpleConfigModel: hasattr(cfg.model, 'registration'): {hasattr(cfg.model, 'registration')}")
                            if hasattr(cfg.model, "registration"):
                                reg_model = cfg.model.registration
                                logger.info(f"🔍 SimpleConfigModel: reg_model type: {type(reg_model)}")
                                logger.info(f"🔍 SimpleConfigModel: reg_model.enabled: {reg_model.enabled}, reg_model.auto_on_startup: {reg_model.auto_on_startup}")
                                registration_enabled = reg_model.enabled and reg_model.auto_on_startup
                                logger.info(f"🔍 Registration enabled check (SimpleConfigModel): {registration_enabled}")
                    except Exception as e:
                        logger.info(f"🔍 SimpleConfigModel check failed: {e}")
                        import traceback
                        logger.info(f"🔍 SimpleConfigModel check traceback: {traceback.format_exc()}")
                    
                    # Also check old formats and new registration section
                    if not registration_enabled:
                        proxy_client_config = current_config.get("proxy_client") or {}
                        proxy_registration_config = current_config.get("proxy_registration") or {}
                        registration_config = current_config.get("registration") or {}
                        
                        logger.info(f"🔍 Checking config sections:")
                        logger.info(f"🔍   proxy_client_config: {proxy_client_config}")
                        logger.info(f"🔍   proxy_registration_config: {proxy_registration_config}")
                        logger.info(f"🔍   registration_config: {registration_config}")
                        logger.info(f"🔍   registration_config type: {type(registration_config)}")
                        
                        # Check new format (registration section)
                        if registration_config:
                            logger.info(f"🔍 registration_config is not empty, checking values...")
                            reg_enabled = registration_config.get("enabled", False)
                            reg_auto_startup = registration_config.get("auto_on_startup", True)
                            logger.info(f"🔍   reg_enabled: {reg_enabled} (type: {type(reg_enabled)})")
                            logger.info(f"🔍   reg_auto_startup: {reg_auto_startup} (type: {type(reg_auto_startup)})")
                            registration_enabled = reg_enabled and reg_auto_startup
                            logger.info(f"🔍 Registration enabled check (registration section): {registration_enabled} (enabled={reg_enabled}, auto_on_startup={reg_auto_startup})")
                        else:
                            logger.info(f"🔍 registration_config is empty or None")
                        
                        # Check old formats if still not enabled
                        if not registration_enabled:
                            logger.info(f"🔍 Checking old formats...")
                            proxy_client_enabled = proxy_client_config.get("enabled", False)
                            proxy_registration_enabled = proxy_registration_config.get("enabled", False)
                            logger.info(f"🔍   proxy_client.enabled: {proxy_client_enabled}")
                            logger.info(f"🔍   proxy_registration.enabled: {proxy_registration_enabled}")
                            registration_enabled = proxy_client_enabled or proxy_registration_enabled
                            logger.info(f"🔍 Registration enabled check (old formats): {registration_enabled}")
                    
                    logger.info(f"🔍 FINAL registration_enabled: {registration_enabled}")
                    if registration_enabled:
                        logger.info("✅ Registration enabled, starting heartbeat task")
                        try:
                            await self.registration_manager.start_heartbeat(current_config)
                        except Exception as e:
                            logger.error(f"❌ Failed to start heartbeat task: {e}", exc_info=True)
                            # Don't fail startup if heartbeat fails - server should still work
                    else:
                        logger.info("⚠️ Registration is disabled, skipping heartbeat task")
                else:
                    logger.info("⚠️ current_config is None, skipping heartbeat task")
            except Exception as e:
                logger.error(f"❌ Lifespan startup failed: {e}", exc_info=True)
                # Don't fail startup - let the server start anyway
                # The error is logged, but the server should still be able to handle requests
            
            yield
            
            # Shutdown
            get_global_logger().info("Shutting down MCP Proxy Adapter")
            await self.registration_manager.stop()

        return lifespan
