"""MCA SDK auto-initialization module.

This module provides automatic MCAClient initialization from environment variables.
It's designed to be used with the mca-run CLI command via sitecustomize.py injection.

Usage:
    # Via mca-run (automatic via PYTHONPATH injection)
    mca-run --model-id mdl-001 --team clinical-ai -- python my_model.py

    # Manual import (if needed, but NOT recommended - use mca-run instead)
    import mca_sdk.cli._bootstrap

Design:
    - Executes _auto_init() on module import (side-effect pattern)
    - Stores client in mca_sdk._auto_client for user access
    - Registers atexit hook with timeout for clean shutdown
    - Gracefully degrades if env vars are missing

CRITICAL: Leading underscore signals internal module (not exported from __init__.py).
This module should ONLY be imported by sitecustomize.py (via mca-run) or explicitly
by users who understand the side-effects.

Remediation Fix: Added timeout to atexit shutdown to prevent hanging if collector is down.
"""

import atexit
import logging
import os
import signal

logger = logging.getLogger(__name__)

# Shutdown timeout (seconds) - prevent hanging if collector is unreachable
SHUTDOWN_TIMEOUT = 3.0


def _shutdown_with_timeout(client, timeout: float = SHUTDOWN_TIMEOUT):
    """Shutdown MCAClient with timeout to prevent hanging.

    Remediation Fix: Ensures shutdown doesn't block indefinitely if collector is down.

    Args:
        client: MCAClient instance
        timeout: Maximum seconds to wait for shutdown
    """

    def _alarm_handler(signum, frame):
        logger.warning("MCA SDK shutdown timed out after %s seconds, forcing exit", timeout)
        # Don't raise - just return and let process exit

    try:
        # Set up timeout alarm (POSIX only)
        if hasattr(signal, "SIGALRM"):
            old_handler = signal.signal(signal.SIGALRM, _alarm_handler)
            signal.alarm(int(timeout))

        # Attempt shutdown
        client.shutdown()

        # Cancel alarm if we completed successfully
        if hasattr(signal, "SIGALRM"):
            signal.alarm(0)
            signal.signal(signal.SIGALRM, old_handler)

    except Exception as e:
        logger.warning("MCA SDK shutdown failed: %s", e)
        # Don't propagate exceptions from atexit handlers


def _auto_init():
    """Initialize MCAClient from MCA_* environment variables.

    This function is called automatically when the module is imported.
    It checks for MCA_MODEL_ID to prevent accidental initialization.

    Returns:
        MCAClient instance if successful, None otherwise
    """
    # Remediation Fix: Only run if MCA_MODEL_ID is set (prevents global side-effects)
    if not os.environ.get("MCA_MODEL_ID"):
        # Not an error - this is expected if bootstrap is imported outside mca-run
        return None

    try:
        from mca_sdk import MCAClient
    except ImportError as e:
        logger.warning("MCA SDK not installed, auto-init skipped: %s", e)
        return None

    # Read required environment variables
    required = {
        "service_name": os.environ.get("MCA_SERVICE_NAME") or os.environ.get("MCA_MODEL_ID"),
        "model_id": os.environ.get("MCA_MODEL_ID"),
        "team_name": os.environ.get("MCA_TEAM_NAME"),
    }

    # Check for missing variables
    missing = [k for k, v in required.items() if not v]
    if missing:
        logger.warning(
            "MCA SDK auto-init skipped: missing env vars for %s. "
            "Set MCA_MODEL_ID and MCA_TEAM_NAME.",
            missing,
        )
        return None

    # Optional configuration
    optional = {
        "collector_endpoint": os.environ.get("MCA_COLLECTOR_ENDPOINT"),
        "registry_url": os.environ.get("MCA_REGISTRY_URL"),
        "use_gcp_auth": os.environ.get("MCA_USE_GCP_AUTH", "false").lower() == "true",
        "allow_insecure_collector": os.environ.get("MCA_ALLOW_INSECURE_COLLECTOR", "false").lower()
        == "true",
        "model_version": os.environ.get("MCA_MODEL_VERSION"),
        "model_type": os.environ.get("MCA_MODEL_TYPE"),
        "model_category": os.environ.get("MCA_MODEL_CATEGORY"),
        "environment": os.environ.get("MCA_ENV"),
        "gcp_logging_enabled": os.environ.get("MCA_GCP_LOGGING_ENABLED", "false").lower() == "true",
        "gcp_project_id": os.environ.get("MCA_GCP_PROJECT_ID"),
        "gcp_log_name": os.environ.get("MCA_GCP_LOG_NAME"),
        "gcp_trace_enabled": os.environ.get("MCA_GCP_TRACE_ENABLED", "false").lower() == "true",
    }

    # Filter out None values
    config = {**required}
    config.update({k: v for k, v in optional.items() if v is not None})

    # Initialize client
    try:
        client = MCAClient(**config)

        # Store globally for user access (follows MLflow pattern)
        import mca_sdk

        mca_sdk._auto_client = client

        # Story 8.5: Silently invoke autolog() to enable auto-instrumentation
        # This enables structured telemetry capture for sklearn, xgboost, etc.
        # Issue #6 Fix: Add kill switch to disable autolog in production if needed
        if os.environ.get("MCA_DISABLE_AUTOLOG", "").lower() not in ("1", "true", "yes"):
            try:
                from mca_sdk import autolog

                autolog()  # Patches ML frameworks with unified instrumentation
                logger.info("MCA SDK autolog enabled")
            except ImportError as e:
                # ML framework dependencies missing - graceful degradation
                logger.debug("autolog not enabled (missing dependencies): %s", e)
            except Exception as e:
                # Don't crash mca-instrument if autolog fails
                logger.warning("autolog initialization failed: %s", e)
        else:
            logger.info("MCA SDK autolog disabled via MCA_DISABLE_AUTOLOG")

        # Register shutdown hook with timeout protection
        atexit.register(_shutdown_with_timeout, client, SHUTDOWN_TIMEOUT)

        logger.info(
            "MCA SDK auto-initialized: service=%s, model=%s",
            config["service_name"],
            config["model_id"],
        )
        return client

    except Exception as exc:
        logger.warning("MCA SDK auto-initialization failed: %s", exc)
        return None


# Execute on module import (side-effect pattern)
# This only runs if MCA_MODEL_ID is set (safe guard)
_auto_init()
