"""Subreddit reading tools for Reddit content."""

from mcp.server.fastmcp import FastMCP

from reddit_mcp.reddit_client import get_reddit
from reddit_mcp.serializers import serialize_submission, serialize_subreddit


def get_subreddit_posts(
    subreddit: str,
    sort: str = "hot",
    time_filter: str = "all",
    limit: int = 25,
) -> list[dict]:
    """
    Get posts from a subreddit.

    Use this tool to browse posts from any subreddit. You can sort by different
    methods and apply time filters for top/controversial posts.

    Args:
        subreddit: Name of the subreddit (without r/ prefix, e.g., "python")
        sort: Sort method - "hot", "new", "top", "rising", or "controversial"
        time_filter: Time filter for top/controversial - "hour", "day",
            "week", "month", "year", or "all"
        limit: Number of posts to return (max 100, default 25)

    Returns:
        List of post dictionaries with title, score, url, author,
            comments count, etc.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    limit = min(limit, 100)

    sort_methods = {
        "hot": lambda: sub.hot(limit=limit),
        "new": lambda: sub.new(limit=limit),
        "top": lambda: sub.top(time_filter=time_filter, limit=limit),
        "rising": lambda: sub.rising(limit=limit),
        "controversial": lambda: sub.controversial(
            time_filter=time_filter, limit=limit
        ),
    }
    posts = sort_methods.get(sort, sort_methods["hot"])()

    return [serialize_submission(p) for p in posts]


def get_front_page(
    sort: str = "hot",
    time_filter: str = "all",
    limit: int = 25,
) -> list[dict]:
    """
    Get posts from the authenticated user's front page.

    Use this tool to see posts from subreddits the user is subscribed to,
    similar to browsing reddit.com while logged in.

    Args:
        sort: Sort method - "hot", "new", "top", "rising", or "controversial"
        time_filter: Time filter for top/controversial - "hour", "day",
            "week", "month", "year", or "all"
        limit: Number of posts to return (max 100, default 25)

    Returns:
        List of post dictionaries from the user's subscribed subreddits.
    """
    reddit = get_reddit()
    limit = min(limit, 100)

    sort_methods = {
        "hot": lambda: reddit.front.hot(limit=limit),
        "new": lambda: reddit.front.new(limit=limit),
        "top": lambda: reddit.front.top(time_filter=time_filter, limit=limit),
        "rising": lambda: reddit.front.rising(limit=limit),
        "controversial": lambda: reddit.front.controversial(
            time_filter=time_filter, limit=limit
        ),
    }
    posts = sort_methods.get(sort, sort_methods["hot"])()

    return [serialize_submission(p) for p in posts]


def get_subreddit_info(subreddit: str) -> dict:
    """
    Get metadata and information about a subreddit.

    Use this tool to retrieve details about a subreddit including its description,
    subscriber count, creation date, and other metadata.

    Args:
        subreddit: Name of the subreddit (without r/ prefix, e.g., "python")

    Returns:
        Dictionary with subreddit information including name, title, description,
        subscriber count, creation date, and type.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    return serialize_subreddit(sub)


def get_subreddit_rules(subreddit: str) -> list[dict]:
    """
    Get the rules of a subreddit.

    Use this tool to retrieve the posting and community rules for a subreddit.
    Essential for understanding what content is allowed before posting.

    Args:
        subreddit: Name of the subreddit (without r/ prefix, e.g., "python")

    Returns:
        List of rule dictionaries with short_name, description, kind,
            and other details.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    rules = sub.rules()

    return [
        {
            "short_name": rule.short_name,
            "description": rule.description,
            "kind": rule.kind,
            "violation_reason": rule.violation_reason,
            "created_utc": rule.created_utc,
            "priority": rule.priority,
        }
        for rule in rules
    ]


def get_subreddit_wiki_page(
    subreddit: str,
    page: str = "index",
) -> dict:
    """
    Get content from a subreddit's wiki page.

    Use this tool to read wiki pages from a subreddit, which often contain
    important information like FAQs, guides, or community resources.

    Args:
        subreddit: Name of the subreddit (without r/ prefix, e.g., "python")
        page: Wiki page name (default "index", common pages: "index",
            "faq", "rules")

    Returns:
        Dictionary with page name, content (markdown), and revision metadata.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    wiki_page = sub.wiki[page]

    return {
        "name": wiki_page.name,
        "content_md": wiki_page.content_md,
        "content_html": wiki_page.content_html,
        "revision_by": str(wiki_page.revision_by) if wiki_page.revision_by else None,
        "revision_date": wiki_page.revision_date,
        "may_revise": wiki_page.may_revise,
    }


def register_subreddit_tools(mcp: FastMCP) -> None:
    """Register subreddit reading tools with the MCP server."""
    mcp.tool()(get_subreddit_posts)
    mcp.tool()(get_front_page)
    mcp.tool()(get_subreddit_info)
    mcp.tool()(get_subreddit_rules)
    mcp.tool()(get_subreddit_wiki_page)
