"""Slack messaging tools — send, read, reply, direct messages."""

from slack_mcp_server.client import SlackClient
from slack_mcp_server.config import SlackConfig


def register_messaging_tools(app, config: SlackConfig):
    """Register messaging tools with the FastMCP app."""

    @app.tool()
    async def slack_send_message(channel: str, text: str) -> dict:
        """Send a message to a Slack channel.

        Args:
            channel: Channel name (e.g., '#general') or channel ID (e.g., 'C01234ABCDE')
            text: Message text (supports Slack markdown: *bold*, _italic_, `code`, ```code block```)
        """
        async with SlackClient(bot_token=config.bot_token, user_token=config.user_token) as client:
            result = await client.post_message(channel=channel, text=text)
            return {"success": True, "channel": result["channel"], "timestamp": result["ts"], "permalink": result.get("permalink", "")}

    @app.tool()
    async def slack_read_messages(channel: str, limit: int = 10) -> dict:
        """Read recent messages from a Slack channel.

        Args:
            channel: Channel name or ID to read from
            limit: Number of messages to return (1-100, default: 10)
        """
        limit = min(max(limit, 1), 100)
        async with SlackClient(bot_token=config.bot_token, user_token=config.user_token) as client:
            messages = await client.get_messages(channel=channel, limit=limit)
            return {"success": True, "channel": channel, "count": len(messages), "messages": messages}

    @app.tool()
    async def slack_reply_thread(channel: str, thread_ts: str, text: str) -> dict:
        """Reply to a message thread in Slack.

        Args:
            channel: Channel name or ID where the thread is
            thread_ts: Timestamp of the parent message (the thread identifier, e.g., '1234567890.123456')
            text: Reply text (supports Slack markdown)
        """
        async with SlackClient(bot_token=config.bot_token, user_token=config.user_token) as client:
            result = await client.post_message(channel=channel, text=text, thread_ts=thread_ts)
            return {"success": True, "channel": result["channel"], "timestamp": result["ts"], "thread_ts": thread_ts}

    @app.tool()
    async def slack_send_dm(user_id: str, text: str) -> dict:
        """Send a direct message to a Slack user.

        Args:
            user_id: Slack user ID (e.g., 'U01234ABCDE')
            text: Message text (supports Slack markdown)
        """
        async with SlackClient(bot_token=config.bot_token, user_token=config.user_token) as client:
            result = await client.send_dm(user_id=user_id, text=text)
            return {"success": True, "channel": result["channel"], "timestamp": result["ts"]}
