"""Content moderation tools for Reddit."""

from mcp.server.fastmcp import FastMCP

from reddit_mcp.reddit_client import get_reddit


def approve_item(item_id: str) -> dict:
    """Approve a reported/removed post or comment.

    Use this to approve content that was incorrectly flagged or removed.
    Removes the item from modqueue and marks it as approved.

    Args:
        item_id: Full Reddit ID (t3_ for post, t1_ for comment)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    if item_id.startswith("t3_"):
        item = reddit.submission(id=item_id[3:])
    elif item_id.startswith("t1_"):
        item = reddit.comment(id=item_id[3:])
    else:
        return {
            "success": False,
            "error": "Invalid item_id prefix. Use t3_ for posts or t1_ for comments",
        }

    item.mod.approve()
    return {"success": True, "item_id": item_id, "action": "approved"}


def remove_item(item_id: str, spam: bool = False, reason: str = "") -> dict:
    """Remove a post or comment from the subreddit.

    Use this to remove rule-breaking content. The item will be hidden from
    the subreddit but still accessible via direct link.

    Args:
        item_id: Full Reddit ID (t3_ for post, t1_ for comment)
        spam: Mark as spam (trains spam filter)
        reason: Internal removal reason for mod log

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    if item_id.startswith("t3_"):
        item = reddit.submission(id=item_id[3:])
    elif item_id.startswith("t1_"):
        item = reddit.comment(id=item_id[3:])
    else:
        return {
            "success": False,
            "error": "Invalid item_id prefix. Use t3_ for posts or t1_ for comments",
        }

    item.mod.remove(spam=spam, mod_note=reason)
    return {"success": True, "item_id": item_id, "action": "removed", "spam": spam}


def spam_item(item_id: str) -> dict:
    """Mark a post or comment as spam.

    Use this for spam content. Trains Reddit's spam filter and removes
    the item from the subreddit.

    Args:
        item_id: Full Reddit ID (t3_ for post, t1_ for comment)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    if item_id.startswith("t3_"):
        item = reddit.submission(id=item_id[3:])
    elif item_id.startswith("t1_"):
        item = reddit.comment(id=item_id[3:])
    else:
        return {
            "success": False,
            "error": "Invalid item_id prefix. Use t3_ for posts or t1_ for comments",
        }

    item.mod.remove(spam=True)
    return {"success": True, "item_id": item_id, "action": "marked_as_spam"}


def distinguish_comment(
    comment_id: str, how: str = "yes", sticky: bool = False
) -> dict:
    """Distinguish a comment as moderator or admin.

    Use this to highlight official moderator responses. Can also sticky
    the comment to the top of the thread.

    Args:
        comment_id: Comment ID (with or without t1_ prefix)
        how: Distinction type - "yes" (mod), "no" (remove), "admin", "special"
        sticky: Pin comment to top of thread

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    comment_id = comment_id.replace("t1_", "")
    comment = reddit.comment(id=comment_id)
    comment.mod.distinguish(how=how, sticky=sticky)
    return {
        "success": True,
        "comment_id": f"t1_{comment_id}",
        "action": "distinguished",
        "how": how,
        "sticky": sticky,
    }


def undistinguish_comment(comment_id: str) -> dict:
    """Remove moderator distinction from a comment.

    Use this to remove the green moderator highlight from a comment.

    Args:
        comment_id: Comment ID (with or without t1_ prefix)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    comment_id = comment_id.replace("t1_", "")
    comment = reddit.comment(id=comment_id)
    comment.mod.undistinguish()
    return {
        "success": True,
        "comment_id": f"t1_{comment_id}",
        "action": "undistinguished",
    }


def sticky_post(subreddit: str, post_id: str, slot: int = 1) -> dict:
    """Sticky a post to the top of the subreddit.

    Use this to pin important announcements. Subreddits can have up to 2
    stickied posts (slots 1 and 2).

    Args:
        subreddit: Subreddit name (without r/)
        post_id: Post ID (with or without t3_ prefix)
        slot: Sticky slot (1 or 2, default 1)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    post_id = post_id.replace("t3_", "")
    submission = reddit.submission(id=post_id)
    submission.mod.sticky(state=True, bottom=slot != 1)
    return {
        "success": True,
        "subreddit": subreddit,
        "post_id": f"t3_{post_id}",
        "action": "stickied",
        "slot": slot,
    }


def unsticky_post(post_id: str) -> dict:
    """Remove sticky status from a post.

    Use this to unpin a previously stickied post.

    Args:
        post_id: Post ID (with or without t3_ prefix)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    post_id = post_id.replace("t3_", "")
    submission = reddit.submission(id=post_id)
    submission.mod.sticky(state=False)
    return {"success": True, "post_id": f"t3_{post_id}", "action": "unstickied"}


def set_suggested_sort(post_id: str, sort: str) -> dict:
    """Set the suggested comment sort order for a post.

    Use this to control how comments are displayed by default. Useful for
    Q&A threads, contests, or live discussions.

    Args:
        post_id: Post ID (with or without t3_ prefix)
        sort: Sort order - "confidence", "top", "new", "controversial",
            "old", "random", "qa", "live", "blank" (clear)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    post_id = post_id.replace("t3_", "")
    submission = reddit.submission(id=post_id)
    submission.mod.suggested_sort(sort=sort)
    return {
        "success": True,
        "post_id": f"t3_{post_id}",
        "action": "set_suggested_sort",
        "sort": sort,
    }


def register_content_moderation_tools(mcp: FastMCP) -> None:
    """Register content moderation tools."""
    mcp.tool()(approve_item)
    mcp.tool()(remove_item)
    mcp.tool()(spam_item)
    mcp.tool()(distinguish_comment)
    mcp.tool()(undistinguish_comment)
    mcp.tool()(sticky_post)
    mcp.tool()(unsticky_post)
    mcp.tool()(set_suggested_sort)
