"""
LiteLLM integration for Risicare SDK.

Registers a CustomLogger callback that creates LLM_CALL spans for all
litellm.completion() and litellm.acompletion() calls. Captures unified
model names, token usage, and cost from LiteLLM's own cost calculator.

Span Hierarchy:
    litellm.completion/{model}    [LLM_CALL, gen_ai.system=provider]
      (provider span suppressed)

Suppresses provider instrumentation to avoid duplicate LLM spans — LiteLLM
internally calls OpenAI/Anthropic/etc. SDKs.

Usage (automatic — zero config):
    import risicare
    risicare.init(api_key="rsk-...")
    import litellm
    response = litellm.completion("gpt-4o", messages=[...])  # Traced
"""

from __future__ import annotations

import logging
import threading
from typing import Any

logger = logging.getLogger(__name__)

_instrumented = False
_lock = threading.RLock()


def instrument_litellm(module: Any) -> None:
    """
    Apply instrumentation to LiteLLM module.

    Called by the import hook system when `litellm` is imported.
    Registers a RisicareLiteLLMLogger as a LiteLLM callback.
    """
    global _instrumented
    if _instrumented:
        return

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

            check_version_compatibility("litellm")

            from risicare.integrations.litellm._callback import register_callback

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