from __future__ import annotations
from contextlib import contextmanager
from typing import Optional

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

try:
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter  # type: ignore
except Exception:  # pragma: no cover
    OTLPSpanExporter = None  # type: ignore

_initialized = False

def init_tracing(otlp_endpoint: Optional[str] = None) -> None:
    global _initialized
    if _initialized:
        return
    provider = TracerProvider()
    if otlp_endpoint and OTLPSpanExporter is not None:
        exporter = OTLPSpanExporter(endpoint=otlp_endpoint)
        provider.add_span_processor(SimpleSpanProcessor(exporter))
    trace.set_tracer_provider(provider)
    _initialized = True

@contextmanager
def span(name: str):
    tracer = trace.get_tracer("adi-agentic-agi")
    with tracer.start_as_current_span(name):
        yield
