"""OpenAI Agents SDK integration: expose Skytale channels as agent tools.

Usage::

    from skytale_sdk.integrations import _openai_agents as skytale_oai

    mgr = skytale_oai.create_manager(identity=b"my-agent")
    mgr.create("org/ns/chan")
    agent = Agent(name="my-agent", tools=skytale_oai.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 OpenAI Agents SDK tools bound to *manager*.

    Requires ``openai-agents>=0.1.0``. Install with::

        pip install skytale-sdk[openai-agents]

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

    Returns:
        List of three ``@function_tool``-decorated functions:
        ``skytale_send``, ``skytale_receive``, ``skytale_channels``.
    """
    from agents import function_tool

    @function_tool
    def skytale_send(channel: str, message: str) -> str:
        """Send an encrypted message to a Skytale channel.

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

    @function_tool
    def skytale_receive(channel: str, timeout: Optional[float] = 5.0) -> str:
        """Receive encrypted messages from a Skytale channel.

        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)

    @function_tool
    def skytale_channels() -> str:
        """List all active Skytale encrypted channels."""
        channels = manager.list_channels()
        if not channels:
            return "No active channels"
        return ", ".join(channels)

    return [skytale_send, skytale_receive, skytale_channels]
