"""
AutoGen integration for Risicare SDK.

Supports both AutoGen v0.4+ (autogen_agentchat) and v0.2.x (autogen).
Patches agent message handling and reply generation to create spans
that capture multi-agent conversation flow.

Span Hierarchy (v0.4+):
    autogen.runtime/{chat_name}          [AGENT, role=ORCHESTRATOR]
      autogen.agent/{agent_name}/turn     [AGENT, role=WORKER]
        autogen.message/send               [MESSAGE, phase=COMMUNICATE]
        autogen.generate_reply             [INTERNAL, phase=THINK]
          anthropic.messages.create         [LLM_CALL — from provider]
        autogen.tool/{tool_name}           [TOOL_CALL, phase=ACT]

Span Hierarchy (v0.2.x):
    autogen.chat/{initiator}→{recipient}  [AGENT, role=ORCHESTRATOR]
      autogen.agent/{name}/reply           [AGENT, role=WORKER]
        openai.chat.completions.create      [LLM_CALL — from provider]

Usage (automatic — zero config):
    import risicare
    risicare.init(api_key="rsk-...")
    import autogen
    # Agents automatically traced
"""

from __future__ import annotations

import logging
import threading
from typing import Any

logger = logging.getLogger(__name__)

_instrumented = False
_lock = threading.RLock()


def instrument_autogen(module: Any) -> None:
    """
    Apply instrumentation to AutoGen module.

    Called by the import hook system when `autogen` or `autogen_agentchat`
    is imported. Detects version and applies appropriate patches.
    """
    global _instrumented
    if _instrumented:
        return

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

            check_version_compatibility("autogen")
            check_version_compatibility("autogen-agentchat")

            from risicare.integrations.autogen._patches import patch_autogen

            patch_autogen(module)
            logger.debug("Instrumented AutoGen")
        except Exception as e:
            _instrumented = False
            logger.debug(f"Failed to instrument AutoGen: {e}")
