"""
# flake8: noqa
tracing.py
----------
Distributed tracing integration for HIEROMEM.
Wraps OpenTelemetry to provide tracing capabilities.
"""

import os
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional
import logging

if TYPE_CHECKING:  # pragma: no cover - import is only for typing
    from opentelemetry.trace import Tracer

logger = logging.getLogger(__name__)

# Try to import OpenTelemetry
try:
    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter

    _HAS_OTEL = True
except ImportError:
    _HAS_OTEL = False
    trace = None

_TRACER: Optional["Tracer"] = None

def init_tracing(service_name: str = "hieromem") -> None:
    """Initialize OpenTelemetry tracing."""
    global _TRACER
    if not _HAS_OTEL:
        logger.info("OpenTelemetry not installed, tracing disabled.")
        return

    if _TRACER is not None:
        return

    # Basic configuration for demo purposes
    # In production, this would configure OTLP exporter
    provider = TracerProvider()
    processor = BatchSpanProcessor(ConsoleSpanExporter())
    provider.add_span_processor(processor)
    trace.set_tracer_provider(provider)
    
    _TRACER = trace.get_tracer(service_name)
    logger.info(f"Tracing initialized for service: {service_name}")

def get_tracer() -> Optional["Tracer"]:
    """Get the global tracer."""
    if _TRACER:
        return _TRACER
    if _HAS_OTEL and trace:
        return trace.get_tracer("hieromem")
    return None

@contextmanager
def start_span(name: str, attributes: Optional[Dict[str, Any]] = None) -> Iterator[Optional[Any]]:
    """Start a new span."""
    tracer = get_tracer()
    if tracer:
        with tracer.start_as_current_span(name, attributes=attributes) as span:
            yield span
    else:
        yield None
