"""OpenTelemetry tracing (build plan Section 8).

Tracing is configured only when ``OTEL_EXPORTER_OTLP_ENDPOINT`` is set and the
OpenTelemetry packages are installed (``pip install -e ".[tracing]"``). Otherwise
this is a no-op so the base install stays lean.
"""

from __future__ import annotations

from legate.config import get_settings
from legate.observability.logging import get_logger

logger = get_logger(__name__)


def setup_tracing(app) -> bool:
    settings = get_settings()
    if not settings.otel_exporter_otlp_endpoint:
        return False
    try:
        from opentelemetry import trace
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
        from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
        from opentelemetry.sdk.resources import Resource
        from opentelemetry.sdk.trace import TracerProvider
        from opentelemetry.sdk.trace.export import BatchSpanProcessor
    except ImportError:
        logger.warning(
            "OTEL endpoint set but opentelemetry not installed; " 'run: pip install -e ".[tracing]"'
        )
        return False

    provider = TracerProvider(
        resource=Resource.create({"service.name": settings.otel_service_name})
    )
    provider.add_span_processor(
        BatchSpanProcessor(OTLPSpanExporter(endpoint=settings.otel_exporter_otlp_endpoint))
    )
    trace.set_tracer_provider(provider)
    FastAPIInstrumentor.instrument_app(app)
    logger.info("tracing enabled -> %s", settings.otel_exporter_otlp_endpoint)
    return True
