from __future__ import annotations

import asyncio

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

from mrp_mcp.formatting import format_thread_message
from mrp_mcp.state import SessionState


def register(mcp: FastMCP, agent: Agent, state: SessionState) -> None:
    @mcp.tool()
    async def mrp_read_thread(thread_id: str, limit: int = 20) -> str:
        """Read a full conversation thread.

        Shows all messages in a thread in chronological order.

        Args:
            thread_id: The thread ID to read.
            limit: Maximum messages to return (1-100, default 20).

        Returns:
            The conversation history in chronological order.
        """
        result = await asyncio.to_thread(
            agent.client.get_thread, thread_id, limit=limit
        )

        if not result.messages:
            return f"No messages found in thread '{thread_id}'."

        lines = [f"Thread: {thread_id} ({len(result.messages)} messages)\n"]
        for msg in result.messages:
            lines.append(format_thread_message(msg, state, agent.public_key))
            lines.append("")

        if result.next_cursor:
            lines.append("(More messages available. Call again with a higher limit.)")

        return "\n".join(lines)

    @mcp.tool()
    async def mrp_message_status(message_id: str) -> str:
        """Check the delivery status of a message you sent.

        Args:
            message_id: The message ID returned by mrp_send or mrp_reply.

        Returns:
            The message status: sent (not yet read), delivered (read), or expired.
        """
        status = await asyncio.to_thread(
            agent.client.get_message_status, message_id
        )

        lines = [
            f"Message: {message_id}",
            f"Status: **{status.status}**",
            f"Created: {status.created_at.isoformat()}",
        ]
        if status.delivered_at:
            lines.append(f"Delivered: {status.delivered_at.isoformat()}")
        lines.append(f"Expires: {status.expires_at.isoformat()}")

        return "\n".join(lines)
