"""plyra-instrument-openai: OpenAI SDK instrumentation for plyra-trace."""

from __future__ import annotations

from typing import Any

_instrumented = False


def instrument(
    tracer_provider: Any = None,
    capture_content: bool = True,
    capture_usage: bool = True,
) -> bool:
    """
    Instrument the OpenAI Python SDK to emit plyra-trace spans.

    Works for:
    - openai.chat.completions.create() (sync + async)
    - openai.chat.completions.stream()
    - openai.embeddings.create()
    - ALL models: gpt-4o, gpt-4o-mini, o1, o3-mini, etc.
    - Azure OpenAI (same SDK, different endpoint)
    - LiteLLM proxy (OpenAI-compatible interface)

    Usage:
        import plyra_trace
        from plyra_instrument_openai import instrument

        pt = plyra_trace.init(project="my-agent", endpoint="http://localhost:7700")
        instrument()

        # Now all OpenAI calls are traced automatically:
        client = openai.OpenAI()
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": "hello"}]
        )
        # → LLM span emitted with model, tokens, cost, prompt, completion

    Returns:
        True if instrumentation was applied, False if already instrumented.
    """
    global _instrumented
    if _instrumented:
        return False
    from plyra_instrument_openai._patch import _patch_openai

    _patch_openai(tracer_provider, capture_content, capture_usage)
    _instrumented = True
    return True


def uninstrument() -> None:
    """Remove OpenAI instrumentation patches."""
    global _instrumented
    if not _instrumented:
        return
    from plyra_instrument_openai._patch import _unpatch_openai

    _unpatch_openai()
    _instrumented = False


__all__ = ["instrument", "uninstrument"]
