"""plyra-instrument-langchain: LangChain/LangGraph callback handler for plyra-trace."""

from __future__ import annotations

from typing import Any

_instrumented = False


def instrument(tracer_provider: Any = None) -> None:
    """
    Install the PlyraCallbackHandler globally for LangChain.

    For LangGraph, pass the handler explicitly via config callbacks instead
    (global callbacks don't propagate reliably in all LangGraph versions).

    Usage:
        from plyra_instrument_langchain import instrument, PlyraCallbackHandler

        # Auto-install globally:
        instrument()

        # Or use handler directly:
        handler = PlyraCallbackHandler()
        result = chain.invoke(input, config={"callbacks": [handler]})
    """
    global _instrumented
    if _instrumented:
        return
    from plyra_instrument_langchain._handler import PlyraCallbackHandler

    try:
        from langchain_core.callbacks import get_callback_manager

        mgr = get_callback_manager()
        mgr.add_handler(PlyraCallbackHandler(), inherit=True)
        _instrumented = True
    except Exception:
        # Older LangChain / no global callback manager — silently skip
        _instrumented = True  # Don't re-attempt, handler can be used manually


from plyra_instrument_langchain._handler import PlyraCallbackHandler  # noqa: E402

__all__ = ["instrument", "PlyraCallbackHandler"]
