# pylint: disable=broad-exception-caught,import-outside-toplevel
import logging
from typing import Optional

logger = logging.getLogger(__name__)


def create_temporal_runtime_with_metrics(
    enabled: bool = False,
    port: int = 9091,
    bind_address: str = "0.0.0.0",
) -> Optional["Runtime"]:
    """
    Create a Temporal runtime with optional Prometheus metrics exposure.

    Args:
        enabled: Whether to enable Prometheus metrics. If False, returns None.
        port: Port to expose metrics endpoint on (default: 9091)
        bind_address: Address to bind the metrics server to (default: 0.0.0.0)

    Returns:
        Runtime instance with Prometheus configured, or None if disabled or failed.
    """
    if not enabled:
        logger.debug("Prometheus metrics disabled")
        return None

    try:
        from temporalio.runtime import PrometheusConfig, Runtime, TelemetryConfig

        bind = f"{bind_address}:{port}"
        logger.info(f"Initializing Temporal runtime with Prometheus metrics at {bind}")

        try:
            runtime = Runtime(
                telemetry=TelemetryConfig(metrics=PrometheusConfig(bind_address=bind))
            )
            logger.info(
                f"✅ Prometheus metrics enabled - endpoint: http://{bind_address}:{port}/metrics"
            )
            return runtime

        except (OSError, ValueError) as e:
            error_msg = str(e).lower()
            if "address already in use" in error_msg or "address in use" in error_msg:
                logger.warning(
                    f"⚠️  Prometheus metrics disabled - port {port} already in use. "
                    f"Worker will continue without metrics."
                )
            else:
                logger.warning(
                    f"⚠️  Prometheus metrics disabled - failed to bind to {bind}: {e}. "
                    f"Worker will continue without metrics."
                )
            return None

    except ImportError as e:
        logger.warning(
            f"⚠️  Prometheus metrics require temporalio>=1.18.1. "
            f"Current installation missing required modules: {e}. "
            f"Worker will continue without metrics."
        )
        return None

    except Exception as e:
        logger.error(
            f"❌ Failed to initialize Prometheus metrics: {e}. "
            f"Worker will continue without metrics.",
            exc_info=True,
        )
        return None
