"""Pydantic AI instrumentation for OpenTelemetry."""

from typing import Optional
from opentelemetry.sdk.trace import TracerProvider


def instrument_pydantic_ai(
    tracer_provider: Optional[TracerProvider] = None,
    renderer: Optional[object] = None
) -> None:
    """Instrument Pydantic AI for OpenTelemetry tracing.

    Args:
        tracer_provider: Optional tracer provider. Uses global if None.
        renderer: Optional custom renderer for Pydantic AI spans.

    Raises:
        ImportError: If pydantic-ai is not installed.
    """
    try:
        from pydantic_ai import Agent
        from pydantic_ai.models.instrumented import InstrumentationSettings
    except ImportError:
        raise ImportError(
            "pydantic-ai is required for instrumentation. "
            "Install with: pip install pydantic-ai"
        )

    if tracer_provider is None:
        from opentelemetry import trace
        tracer_provider = trace.get_tracer_provider()

    instrumentation_settings = InstrumentationSettings(tracer_provider=tracer_provider)
    Agent.instrument_all(instrumentation_settings)

    # Register custom renderer if provided
    if renderer is not None:
        # Register renderer for spans with gen_ai.operation.name attribute
        from .. import streamer
        if hasattr(streamer, '_global_streamer') and streamer._global_streamer:
            streamer._global_streamer.register_attribute_renderer("gen_ai.operation.name", renderer)