"""Reddit saved items tools."""

from mcp.server.fastmcp import FastMCP
from praw.models import Comment, Submission

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


def get_saved_items(limit: int = 25) -> dict:
    """Retrieve the user's saved submissions and comments.

    Use this tool when the user wants to view their bookmarked content.
    Returns a list of saved posts and comments with full details.

    Args:
        limit: Maximum number of saved items to retrieve (default: 25, max: 100)

    Returns:
        Dictionary containing lists of saved submissions and comments
            with full metadata

    Examples:
        - get_saved_items() - Get 25 most recent saved items
        - get_saved_items(50) - Get 50 most recent saved items

    Note: Items are returned in reverse chronological order
        (most recently saved first).
    """
    reddit = get_reddit()
    limit = min(limit, 100)

    me = reddit.user.me()
    if me is None:
        return {"success": False, "error": "Not authenticated"}

    saved_items = list(me.saved(limit=limit))

    submissions = []
    comments = []

    for item in saved_items:
        if isinstance(item, Submission):
            submissions.append(serialize_submission(item))
        elif isinstance(item, Comment):
            comments.append(serialize_comment(item))

    return {
        "success": True,
        "total_items": len(saved_items),
        "submissions_count": len(submissions),
        "comments_count": len(comments),
        "submissions": submissions,
        "comments": comments,
    }


def register_saved_tools(mcp: FastMCP) -> None:
    """Register saved items tools."""
    mcp.tool()(get_saved_items)
