"""Reddit user settings and preferences tools."""

import re

from mcp.server.fastmcp import FastMCP
from prawcore.exceptions import BadRequest

from reddit_mcp.reddit_client import get_reddit


def register_settings_tools(mcp: FastMCP) -> None:
    """Register user settings tools."""

    @mcp.tool()
    def get_preferences() -> dict:
        """Get the authenticated user's account preferences.

        Retrieves all account settings and preferences including display options,
        privacy settings, notification preferences, and content filters.

        Returns:
            dict: Complete preferences object with all settings
        """
        reddit = get_reddit()
        prefs = reddit.user.preferences()
        return dict(prefs)

    @mcp.tool()
    def update_preferences(**kwargs: str | bool | int) -> dict:
        """Update the authenticated user's account preferences.

        Modifies account settings. Only provided parameters will be updated,
        others remain unchanged. Common preferences include:
        - show_trending: Show trending posts
        - enable_followers: Allow others to follow you
        - show_presence: Show online presence
        - accept_pms: Who can send private messages ("everyone" or "whitelisted")

        Args:
            **kwargs: Preference key-value pairs to update

        Returns:
            dict: Updated preferences object
        """
        reddit = get_reddit()
        reddit.user.preferences.update(**kwargs)
        # Fetch updated preferences
        updated_prefs = reddit.user.preferences()
        return dict(updated_prefs)

    @mcp.tool()
    def get_multireddits() -> list[dict]:
        """Get the authenticated user's multireddits.

        Retrieves all custom multireddits (collections of subreddits) created
        by the authenticated user. Multireddits allow viewing multiple subreddits
        as a single feed.

        Returns:
            list[dict]: List of multireddits with name, description, and subreddits
        """
        reddit = get_reddit()
        multis = reddit.user.multireddits()
        return [
            {
                "name": multi.name,
                "display_name": multi.display_name,
                "description": multi.description_md
                if hasattr(multi, "description_md")
                else None,
                "subreddits": [str(sub) for sub in multi.subreddits],
                "path": multi.path,
                "visibility": multi.visibility
                if hasattr(multi, "visibility")
                else None,
            }
            for multi in multis
        ]

    @mcp.tool()
    def create_multireddit(
        name: str,
        subreddits: list[str],
        description: str = "",
        visibility: str = "private",
    ) -> dict:
        """Create a new multireddit.

        Creates a custom collection of subreddits that can be viewed as a single
        feed. Useful for grouping related communities.

        Args:
            name: Name for the multireddit (alphanumeric and underscores only)
            subreddits: List of subreddit names to include (without r/ prefix)
            description: Optional description in markdown format
            visibility: "private", "public", or "hidden" (default: "private")

        Returns:
            dict: Created multireddit details including path and subreddit list
        """
        reddit = get_reddit()
        multi = reddit.multireddit.create(
            display_name=name,
            subreddits=subreddits,
            description_md=description,
            visibility=visibility,
        )
        return {
            "name": multi.name,
            "display_name": multi.display_name,
            "description": multi.description_md
            if hasattr(multi, "description_md")
            else None,
            "subreddits": [str(sub) for sub in multi.subreddits],
            "path": multi.path,
            "visibility": multi.visibility if hasattr(multi, "visibility") else None,
        }

    @mcp.tool()
    def is_username_available(username: str) -> dict:
        """Check if a username is available for registration."""
        if not re.match(r"^[a-zA-Z0-9_-]{3,20}$", username):
            return {
                "username": username,
                "available": False,
                "error": "Invalid format. "
                "Must be 3-20 chars, alphanumeric/underscore/hyphen",
            }

        reddit = get_reddit()
        try:
            available = reddit.username_available(username)
        except BadRequest as e:
            return {
                "username": username,
                "available": False,
                "error": f"Reddit rejected: {e!s}",
            }
        else:
            return {"username": username, "available": available}
