"""Optional observability layer -- requires the `otel` extra
(`pip install a2a-passport[otel]`). Importing this module without the extra
installed raises a clear ImportError rather than a confusing one deep in
opentelemetry internals.

One call wires up OTel for an agent process: FastAPI/ASGI server spans and
outbound httpx client spans, console-exported by default. Swap
ConsoleSpanExporter for OTLPSpanExporter pointed at your collector in
production -- nothing else in the library touches the tracer directly.
"""
from __future__ import annotations

try:
    from opentelemetry import trace
    from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
    from opentelemetry.sdk.resources import SERVICE_NAME, Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
except ImportError as exc:  # pragma: no cover
    raise ImportError(
        "a2a_passport.tracing requires the 'otel' extra: "
        "pip install a2a-passport[otel]"
    ) from exc

_configured = False


def setup_tracing(service_name: str, *, span_processor=None) -> None:
    """Configure a global TracerProvider for this process. Idempotent."""
    global _configured
    if _configured:
        return
    resource = Resource.create({SERVICE_NAME: service_name})
    provider = TracerProvider(resource=resource)
    provider.add_span_processor(span_processor or SimpleSpanProcessor(ConsoleSpanExporter()))
    trace.set_tracer_provider(provider)
    HTTPXClientInstrumentor().instrument()
    _configured = True


def instrument_asgi_app(app, service_name: str, *, span_processor=None) -> None:
    """Call once per server process, after (or in lieu of) setup_tracing()."""
    from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

    setup_tracing(service_name, span_processor=span_processor)
    FastAPIInstrumentor.instrument_app(app)
