"""LangGraph integration: expose Skytale encrypted channels as LangChain tools.

Usage::

    from skytale_sdk.integrations import _langgraph as skytale_lg

    mgr = skytale_lg.create_manager(identity=b"my-agent")
    mgr.create("org/ns/chan")
    agent = create_react_agent(llm, skytale_lg.tools(mgr))
"""

from __future__ import annotations

from typing import Optional

from skytale_sdk.channels import SkytaleChannelManager


def create_manager(**kwargs) -> SkytaleChannelManager:
    """Create a ``SkytaleChannelManager`` with the given options.

    Accepts the same keyword arguments as ``SkytaleChannelManager``.

    Returns:
        A configured channel manager.
    """
    return SkytaleChannelManager(**kwargs)


def tools(manager: SkytaleChannelManager) -> list:
    """Return LangChain-compatible tools bound to *manager*.

    Requires ``langchain-core>=0.3.0``. Install with::

        pip install skytale-sdk[langgraph]

    Args:
        manager: A ``SkytaleChannelManager`` managing the channels.

    Returns:
        List of three ``@tool``-decorated functions:
        ``skytale_send``, ``skytale_receive``, ``skytale_channels``.
    """
    from langchain_core.tools import tool

    @tool
    def skytale_send(channel: str, message: str) -> str:
        """Send an encrypted message to an AI agent channel.

        Use this tool to send a message to other agents listening on the
        specified Skytale encrypted channel. Messages are end-to-end
        encrypted using the MLS protocol.

        Args:
            channel: Channel name in org/namespace/service format
                (e.g. "acme/research/results").
            message: The message text to send.
        """
        manager.send(channel, message)
        return f"Message sent to {channel}"

    @tool
    def skytale_receive(channel: str, timeout: Optional[float] = 5.0) -> str:
        """Receive encrypted messages from an AI agent channel.

        Use this tool to check for new messages on the specified Skytale
        encrypted channel. Returns all messages received since the last
        check, or waits up to *timeout* seconds for new ones.

        Args:
            channel: Channel name in org/namespace/service format.
            timeout: Seconds to wait for messages (default 5).
        """
        msgs = manager.receive(channel, timeout=timeout or 5.0)
        if not msgs:
            return f"No new messages on {channel}"
        return "\n".join(f"[{channel}] {m}" for m in msgs)

    @tool
    def skytale_channels() -> str:
        """List all active Skytale encrypted channels.

        Returns the names of channels this agent has created or joined.
        """
        channels = manager.list_channels()
        if not channels:
            return "No active channels"
        return ", ".join(channels)

    return [skytale_send, skytale_receive, skytale_channels]
