"""
OpenAI Agents SDK integration for Risicare SDK.

Patches Runner.run/run_sync to wrap agent execution in spans.
Handoffs between agents become DELEGATION spans. Does NOT suppress
provider instrumentation — lets the OpenAI provider patch handle
LLM calls naturally as children.

Span Hierarchy:
    openai_agents.run/{agent_name}        [AGENT, role=ORCHESTRATOR]
      openai_agents.agent/{agent_name}     [AGENT, role=WORKER]
        openai.chat.completions.create      [LLM_CALL — from provider]
        openai_agents.tool/{tool_name}      [TOOL_CALL, phase=ACT]
      openai_agents.handoff/{from}→{to}    [DELEGATION, phase=COORDINATE]
      openai_agents.agent/{next_agent}      [AGENT, role=WORKER]

Usage (automatic — zero config):
    import risicare
    risicare.init(api_key="rsk-...")
    from agents import Agent, Runner
    result = Runner.run_sync(agent, "hello")  # Automatically traced
"""

from __future__ import annotations

import logging
import threading
from typing import Any

logger = logging.getLogger(__name__)

_instrumented = False
_lock = threading.Lock()


def instrument_openai_agents(module: Any) -> None:
    """
    Apply instrumentation to OpenAI Agents SDK.

    Called by the import hook system when `agents` is imported.
    Patches Runner.run and Runner.run_sync.
    """
    global _instrumented
    if _instrumented:
        return

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

            check_version_compatibility("openai-agents")

            from risicare.integrations.openai_agents._patches import patch_openai_agents

            patch_openai_agents(module)
            _instrumented = True
            logger.debug("Instrumented OpenAI Agents SDK")
        except Exception as e:
            logger.debug(f"Failed to instrument OpenAI Agents SDK: {e}")
