"""MCP server exposing Skytale encrypted channels.

Run as::

    SKYTALE_IDENTITY=my-agent python -m skytale_sdk.integrations._mcp

Works with any MCP client: Claude Desktop, LangGraph, CrewAI, etc.
"""

from __future__ import annotations

import os

from mcp.server.fastmcp import FastMCP

from skytale_sdk.channels import SkytaleChannelManager

_identity = os.environ.get("SKYTALE_IDENTITY", "mcp-agent")
_manager = SkytaleChannelManager(identity=_identity.encode())

mcp = FastMCP("skytale")


@mcp.tool()
def skytale_create_channel(channel: str) -> str:
    """Create a new encrypted channel.

    Creates an MLS-encrypted channel and starts listening for messages.

    Args:
        channel: Channel name in org/namespace/service format
            (e.g. "acme/research/results").
    """
    _manager.create(channel)
    return f"Channel {channel} created"


@mcp.tool()
def skytale_key_package() -> str:
    """Generate an MLS key package for joining a channel.

    Returns a hex-encoded key package. Send this to the channel creator
    so they can call skytale_add_member to add you.
    """
    kp = _manager.key_package()
    return kp.hex()


@mcp.tool()
def skytale_add_member(channel: str, key_package_hex: str) -> str:
    """Add a member to a channel using their key package.

    Args:
        channel: Channel name to add the member to.
        key_package_hex: Hex-encoded MLS key package from skytale_key_package.

    Returns:
        Hex-encoded MLS Welcome message. Send this to the joining agent
        so they can call skytale_join_channel.
    """
    kp = bytes.fromhex(key_package_hex)
    welcome = _manager.add_member(channel, kp)
    return welcome.hex()


@mcp.tool()
def skytale_join_channel(channel: str, welcome_hex: str) -> str:
    """Join an existing channel using an MLS Welcome message.

    Args:
        channel: Channel name to join.
        welcome_hex: Hex-encoded Welcome message from skytale_add_member.
    """
    welcome = bytes.fromhex(welcome_hex)
    _manager.join(channel, welcome)
    return f"Joined channel {channel}"


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

    Messages are end-to-end encrypted using the MLS protocol. All members
    of the channel will receive the message.

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


@mcp.tool()
def skytale_receive(channel: str, timeout: float = 5.0) -> str:
    """Receive messages from an encrypted channel.

    Returns all messages received since the last check, or waits up to
    timeout seconds for new messages.

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


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


if __name__ == "__main__":
    mcp.run(transport="stdio")
