"""Modqueue and reports tools for Reddit."""

from mcp.server.fastmcp import FastMCP

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


def get_modqueue(subreddit: str, limit: int = 25) -> dict:
    """Get items in the moderation queue.

    Use this to view posts and comments that need moderator review
    (reported, filtered, or removed items).

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of items to return (default 25)

    Returns:
        List of items in modqueue with details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    items = []

    for item in sub.mod.modqueue(limit=limit):
        if hasattr(item, "title"):
            items.append(serialize_submission(item))
        else:
            items.append(serialize_comment(item))

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(items),
        "items": items,
    }


def get_reports(subreddit: str, limit: int = 25) -> dict:
    """Get reported items in a subreddit.

    Use this to view posts and comments that have been reported by users.

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of items to return (default 25)

    Returns:
        List of reported items with report details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    items = []

    for item in sub.mod.reports(limit=limit):
        if hasattr(item, "title"):
            items.append(serialize_submission(item))
        else:
            items.append(serialize_comment(item))

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(items),
        "items": items,
    }


def get_spam(subreddit: str, limit: int = 25) -> dict:
    """Get items in the spam queue.

    Use this to view posts and comments marked as spam by filters or
    moderators.

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of items to return (default 25)

    Returns:
        List of spam items
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    items = []

    for item in sub.mod.spam(limit=limit):
        if hasattr(item, "title"):
            items.append(serialize_submission(item))
        else:
            items.append(serialize_comment(item))

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(items),
        "items": items,
    }


def get_edited(subreddit: str, limit: int = 25) -> dict:
    """Get recently edited items in a subreddit.

    Use this to review posts and comments that have been edited by users.

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of items to return (default 25)

    Returns:
        List of edited items
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    items = []

    for item in sub.mod.edited(limit=limit):
        if hasattr(item, "title"):
            items.append(serialize_submission(item))
        else:
            items.append(serialize_comment(item))

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(items),
        "items": items,
    }


def get_unmoderated(subreddit: str, limit: int = 25) -> dict:
    """Get unmoderated posts in a subreddit.

    Use this to view new posts that haven't been reviewed by moderators yet.

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of posts to return (default 25)

    Returns:
        List of unmoderated posts
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    items = [serialize_submission(item) for item in sub.mod.unmoderated(limit=limit)]

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(items),
        "items": items,
    }


def get_mod_log(
    subreddit: str, limit: int = 100, mod: str = "", action: str = ""
) -> dict:
    """Get moderation log entries.

    Use this to view the history of moderator actions in the subreddit.
    Can filter by moderator or action type.

    Args:
        subreddit: Subreddit name (without r/)
        limit: Maximum number of log entries to return (default 100)
        mod: Filter by moderator username (optional)
        action: Filter by action type - "banuser", "unbanuser",
            "removelink", "approvelink", etc. (optional)

    Returns:
        List of moderation log entries
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)

    kwargs: dict[str, int | str | object] = {"limit": limit}
    if mod:
        kwargs["mod"] = reddit.redditor(mod)
    if action:
        kwargs["action"] = action

    log_entries = [
        {
            "id": entry.id,
            "action": entry.action,
            "mod": str(getattr(entry, "_mod", "")),
            "target_author": str(entry.target_author) if entry.target_author else None,
            "target_fullname": entry.target_fullname,
            "target_permalink": entry.target_permalink,
            "details": entry.details,
            "description": entry.description,
            "created_utc": entry.created_utc,
        }
        for entry in sub.mod.log(**kwargs)
    ]

    return {
        "success": True,
        "subreddit": subreddit,
        "count": len(log_entries),
        "log_entries": log_entries,
    }


def register_queue_moderation_tools(mcp: FastMCP) -> None:
    """Register modqueue and reports tools."""
    mcp.tool()(get_modqueue)
    mcp.tool()(get_reports)
    mcp.tool()(get_spam)
    mcp.tool()(get_edited)
    mcp.tool()(get_unmoderated)
    mcp.tool()(get_mod_log)
