import pytest

from frisk_sdk.adapters.langchain import FriskLangchainSession
from frisk_sdk.adapters.langchain.langchain_framework_adapter import (
    LangchainFrameworkAdapter,
)


@pytest.fixture
def frisk_langchain_instance(monkeypatch: pytest.MonkeyPatch):
    """Create a FriskLangchain without running CoreFrisk.__init__ (avoids Rust/threads)."""

    from frisk_sdk.adapters.langchain.frisk_langchain import FriskLangchain

    def _noop_init(self, *args, **kwargs):
        # Minimal attributes needed by the adapter helpers.
        self.logger_name = "frisk.test"
        self.logger = {}
        self.redaction = {}
        self._adapter = LangchainFrameworkAdapter()

        # FriskLangchain.session() expects _tracing_manager.get_tracer()
        class _TM:
            def get_tracer(self):
                return object()

        self._tracing_manager = _TM()

    monkeypatch.setattr(FriskLangchain, "__init__", _noop_init)
    return FriskLangchain(api_key="k")


@pytest.mark.unit
def test_callback_handler_returns_frisk_callback_handler(
    frisk_langchain_instance, monkeypatch: pytest.MonkeyPatch
):
    from frisk_sdk.adapters.langchain.frisk_callback_handler import FriskCallbackHandler

    # FriskCallbackHandler resolves the session from SessionRegistry in __init__.
    # Patch that lookup to avoid needing a real FriskSession.

    session = frisk_langchain_instance.session()
    assert isinstance(session, FriskLangchainSession)
    assert isinstance(session.callbacks, FriskCallbackHandler)
    assert session.frisk is frisk_langchain_instance


@pytest.mark.unit
def test_tool_middleware_returns_frisk_tool_middleware(frisk_langchain_instance):
    from frisk_sdk.adapters.langchain.frisk_tool_middleware import FriskToolMiddleware

    mw = frisk_langchain_instance.guard()
    assert isinstance(mw, FriskToolMiddleware)
    assert mw._frisk_handle is frisk_langchain_instance
