import logging
from typing import Optional, Any  # Any used for setup_fastapi app parameter
from .config import ObservabilityConfig

logger = logging.getLogger(__name__)

_HEALTH_CHECK_EXCLUDED_URLS = "health_check,healthcheck,health,ping"


def setup_django():
    try:
        from opentelemetry.instrumentation.django import DjangoInstrumentor

        DjangoInstrumentor().instrument(excluded_urls=_HEALTH_CHECK_EXCLUDED_URLS)

        if not ObservabilityConfig.OTEL_FILTER_DATABASE_SPANS:
            from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
            Psycopg2Instrumentor().instrument()
            logger.info("Django and PostgreSQL instrumentation enabled")
        else:
            logger.info("Django instrumentation enabled (PostgreSQL spans will be filtered)")

        return True
    except Exception as e:
        logger.warning(f"Django instrumentation failed: {e}")
        return False


def setup_fastapi(app: Optional[Any] = None):
    try:
        from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
        from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

        if app:
            FastAPIInstrumentor().instrument_app(app, excluded_urls=_HEALTH_CHECK_EXCLUDED_URLS)
        HTTPXClientInstrumentor().instrument()
        logger.info("FastAPI instrumentation enabled")
        return True
    except Exception as e:
        logger.warning(f"FastAPI instrumentation failed: {e}")
        return False

def setup_celery():
    """
    Celery instrumentation is handled by our custom celery_instrumentation.py
    which properly handles tenant_id propagation and trace context.
    
    The built-in CeleryInstrumentor is disabled to avoid conflicts.
    """
    # NOTE: We use custom instrumentation from celery_instrumentation.py instead
    # of the built-in CeleryInstrumentor to properly handle tenant_id and
    # ensure trace context is correctly attached for logging.
    logger.info("Celery instrumentation delegated to custom celery_instrumentation module")
    return True
