"""Shared helpers for interaction tools."""

from collections.abc import Callable
from typing import Any

from praw.models import Comment, Submission

from reddit_mcp.reddit_client import get_reddit

INVALID_PREFIX_ERROR = {
    "success": False,
    "error": "Invalid item_id prefix. Use t3_ for posts, t1_ for comments",
}


def get_item_by_id(item_id: str) -> tuple[Submission | Comment | None, str]:
    """Get a Reddit item by its full ID.

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

    Returns:
        Tuple of (item, item_type) where item_type is "submission" or "comment".
        Returns (None, "") if the prefix is invalid.
    """
    reddit = get_reddit()

    if item_id.startswith("t3_"):
        return reddit.submission(id=item_id[3:]), "submission"
    if item_id.startswith("t1_"):
        return reddit.comment(id=item_id[3:]), "comment"
    return None, ""


def perform_item_action(
    item_id: str,
    action_name: str,
    action_fn: Callable[[Submission | Comment], None],
    extra_fields: dict[str, Any] | None = None,
) -> dict:
    """Perform an action on a Reddit item and return a standardized response.

    Args:
        item_id: Full Reddit ID with prefix
        action_name: Name of the action for the response (e.g., "upvoted", "saved")
        action_fn: Function to call on the item
        extra_fields: Additional fields to include in the success response

    Returns:
        Standardized success or error response dict.
    """
    item, item_type = get_item_by_id(item_id)

    if item is None:
        return INVALID_PREFIX_ERROR

    action_fn(item)

    result = {
        "success": True,
        "item_id": item_id,
        "action": action_name,
        "type": item_type,
    }

    if extra_fields:
        result.update(extra_fields)

    return result
