"""LangChain integration via MCP."""
from __future__ import annotations

from contextlib import asynccontextmanager


@asynccontextmanager
async def get_langchain_tools(
    api_key: str,
    base_url: str = "https://api.dialogbrain.com",
):
    """
    Async context manager that yields LangChain-compatible tools from DialogBrain's MCP server.

    All registered DialogBrain tools are fetched live — adding a new tool to DialogBrain
    requires zero SDK update.

    Requires: pip install "dialogbrain[langchain]"

    Usage::

        from dialogbrain import get_langchain_tools
        from langgraph.prebuilt import create_react_agent

        async with get_langchain_tools(api_key="db_live_...") as tools:
            agent = create_react_agent(llm, tools)
            result = await agent.ainvoke({"messages": [{"role": "user", "content": "..."}]})
    """
    try:
        from mcp import ClientSession
        from mcp.client.streamable_http import streamablehttp_client
        from langchain_mcp_adapters.tools import load_mcp_tools
    except ImportError as e:
        raise ImportError(
            "LangChain support requires additional dependencies. "
            'Install with: pip install "dialogbrain[langchain]"'
        ) from e

    async with streamablehttp_client(
        f"{base_url}/mcp",
        headers={"X-API-Key": api_key},
    ) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await load_mcp_tools(session)
            yield tools
