"""
Pydantic AI integration for Risicare SDK.

Patches Agent.run(), Agent.run_sync(), and Agent.run_stream() to create
AGENT spans around agent execution. Does NOT suppress provider
instrumentation — lets OpenAI/Anthropic provider patches create LLM
spans naturally as children (same pattern as CrewAI).

Span Hierarchy:
    pydantic_ai.agent.run/{agent_name}     [AGENT, span_kind="agent"]
      openai.chat.completions.create/{model} [LLM_CALL — from provider patch]

Usage (automatic — zero config):
    import risicare
    risicare.init(api_key="rsk-...")
    from pydantic_ai import Agent
    agent = Agent("openai:gpt-4o", system_prompt="You are helpful.")
    result = agent.run_sync("Hello")  # Traced
"""

from __future__ import annotations

import logging
import threading
from typing import Any

logger = logging.getLogger(__name__)

_instrumented = False
_lock = threading.Lock()


def instrument_pydantic_ai(module: Any) -> None:
    """
    Apply instrumentation to Pydantic AI module.

    Called by the import hook system when `pydantic_ai` is imported.
    """
    global _instrumented
    if _instrumented:
        return

    with _lock:
        if _instrumented:
            return
        try:
            from risicare.integrations._base import check_version_compatibility

            check_version_compatibility("pydantic-ai")

            from risicare.integrations.pydantic_ai._patches import patch_pydantic_ai

            patch_pydantic_ai(module)
            _instrumented = True
            logger.debug("Instrumented Pydantic AI")
        except Exception as e:
            logger.debug(f"Failed to instrument Pydantic AI: {e}")
