"""CrewAI integration: expose Skytale encrypted channels as CrewAI tools.

Usage::

    from skytale_sdk.integrations import _crewai as skytale_crew

    mgr = skytale_crew.create_manager(identity=b"analyst")
    mgr.create("org/ns/chan")
    analyst = Agent(role="Analyst", tools=skytale_crew.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 CrewAI-compatible tools bound to *manager*.

    Requires ``crewai>=0.80.0``. Install with::

        pip install skytale-sdk[crewai]

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

    Returns:
        List of three ``BaseTool`` instances:
        ``SkytaleSendTool``, ``SkytaleReceiveTool``, ``SkytaleChannelsTool``.
    """
    from crewai.tools import BaseTool
    from pydantic import BaseModel, Field

    class SendInput(BaseModel):
        channel: str = Field(description="Channel name (org/namespace/service)")
        message: str = Field(description="Message text to send")

    class ReceiveInput(BaseModel):
        channel: str = Field(description="Channel name (org/namespace/service)")
        timeout: float = Field(default=5.0, description="Seconds to wait")

    class SkytaleSendTool(BaseTool):
        name: str = "skytale_send"
        description: str = (
            "Send an encrypted message to an AI agent channel. "
            "Messages are end-to-end encrypted using the MLS protocol."
        )
        args_schema: type[BaseModel] = SendInput

        def _run(self, channel: str, message: str) -> str:
            manager.send(channel, message)
            return f"Message sent to {channel}"

    class SkytaleReceiveTool(BaseTool):
        name: str = "skytale_receive"
        description: str = (
            "Receive encrypted messages from an AI agent channel. "
            "Returns all messages received since the last check."
        )
        args_schema: type[BaseModel] = ReceiveInput

        def _run(
            self, channel: str, timeout: Optional[float] = 5.0
        ) -> str:
            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)

    class SkytaleChannelsTool(BaseTool):
        name: str = "skytale_channels"
        description: str = (
            "List all active Skytale encrypted channels that this "
            "agent has created or joined."
        )

        def _run(self) -> str:
            channels = manager.list_channels()
            if not channels:
                return "No active channels"
            return ", ".join(channels)

    return [SkytaleSendTool(), SkytaleReceiveTool(), SkytaleChannelsTool()]
