from __future__ import annotations

import asyncio
import json

from mcp.server.fastmcp import FastMCP
from mrp import Agent

from mrp_mcp.state import SessionState


def register(mcp: FastMCP, agent: Agent, state: SessionState) -> None:
    @mcp.tool()
    async def mrp_whoami() -> str:
        """Show this agent's identity and profile on the MRP network.

        Returns your public key, display name, capabilities, and status.
        """
        info = await asyncio.to_thread(agent.client.get_agent, agent.public_key)

        lines = [
            "**Identity**",
            f"Public key: {info.public_key}",
            f"Display name: {info.display_name or '(not set)'}",
            f"Status: {info.status}",
            f"Capabilities: {', '.join(info.capabilities) if info.capabilities else '(none)'}",
            f"Created: {info.created_at.isoformat()}",
            f"Last active: {info.last_active_at.isoformat()}",
        ]
        if info.metadata:
            lines.append(f"Metadata: {json.dumps(info.metadata)}")

        return "\n".join(lines)

    @mcp.tool()
    async def mrp_update_profile(
        name: str | None = None,
        capabilities: str | None = None,
        metadata: dict | None = None,
    ) -> str:
        """Update this agent's profile on the MRP network.

        Other agents see your profile when they discover you.

        Args:
            name: Display name for this agent.
            capabilities: Comma-separated list of capabilities
                (e.g. "text:chat,text:summarize"). Max 20.
            metadata: Key-value metadata pairs. Max 16 keys, 256 chars each.

        Returns:
            The updated profile.
        """
        caps_list = None
        if capabilities:
            caps_list = [c.strip() for c in capabilities.split(",")]

        info = await asyncio.to_thread(
            agent.client.update_agent,
            agent.public_key,
            display_name=name,
            capabilities=caps_list,
            metadata=metadata,
        )
        caps_str = ", ".join(info.capabilities) if info.capabilities else "(none)"
        return f"Profile updated.\nName: {info.display_name}\nCapabilities: {caps_str}"

    @mcp.tool()
    async def mrp_register_webhook(url: str, secret: str) -> str:
        """Register a webhook URL for push message delivery.

        Instead of polling for messages, the relay will POST messages
        to this URL as they arrive.

        Args:
            url: The publicly reachable HTTPS URL to receive messages.
            secret: A shared secret for HMAC-SHA256 signature verification.

        Returns:
            Confirmation of webhook registration.
        """

        def _register():
            return agent.client._request(
                "PUT",
                f"/v1/agents/{agent.public_key}/webhook",
                body={"url": url, "secret": secret},
            )

        await asyncio.to_thread(_register)
        return f"Webhook registered.\nURL: {url}\nEnabled: true"
