"""Media submission tools for Reddit - image, video, gallery posts."""

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

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


def submit_image_post(
    subreddit: str,
    title: str,
    image_path: str,
    flair_id: str | None = None,
    nsfw: bool = False,
    spoiler: bool = False,
    send_replies: bool = True,
) -> dict:
    """
    Submit an image post to a subreddit.

    Uploads and posts a single image file. Supported formats include JPEG,
    PNG, and GIF. The image will be hosted on Reddit's servers.

    Args:
        subreddit: Target subreddit name (without r/ prefix)
        title: Post title (max 300 characters)
        image_path: Local file path to the image to upload
        flair_id: Optional flair template ID
        nsfw: Mark post as NSFW
        spoiler: Mark post as spoiler (blurs thumbnail)
        send_replies: Receive inbox notifications for replies

    Returns:
        Dictionary with created post details including the hosted image URL

    Example:
        submit_image_post(
            subreddit="pics",
            title="Beautiful Sunset",
            image_path="/path/to/sunset.jpg",
            spoiler=False
        )

    Note:
        Image file must exist at the specified path and be in a supported format.
        Maximum file size varies by subreddit settings.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    result = sub.submit_image(
        title=title,
        image_path=image_path,
        flair_id=flair_id,
        nsfw=nsfw,
        spoiler=spoiler,
        send_replies=send_replies,
    )
    if not isinstance(result, Submission):
        return {"error": "Failed to create image post", "success": False}
    return serialize_submission(result)


def submit_video_post(
    subreddit: str,
    title: str,
    video_path: str,
    thumbnail_path: str | None = None,
    flair_id: str | None = None,
    nsfw: bool = False,
    spoiler: bool = False,
    send_replies: bool = True,
) -> dict:
    """
    Submit a video post to a subreddit.

    Uploads and posts a video file. The video will be hosted on Reddit's
    video player (v.redd.it). Supported formats include MP4, MOV, and others.

    Args:
        subreddit: Target subreddit name (without r/ prefix)
        title: Post title (max 300 characters)
        video_path: Local file path to the video to upload
        thumbnail_path: Optional path to custom thumbnail image
        flair_id: Optional flair template ID
        nsfw: Mark post as NSFW
        spoiler: Mark post as spoiler
        send_replies: Receive inbox notifications for replies

    Returns:
        Dictionary with created post details including the hosted video URL

    Example:
        submit_video_post(
            subreddit="videos",
            title="Amazing Trick Shot",
            video_path="/path/to/video.mp4",
            thumbnail_path="/path/to/thumb.jpg"
        )

    Note:
        Video upload may take time depending on file size. Maximum duration
        and file size limits vary by subreddit. Reddit will process the video
        after upload.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    result = sub.submit_video(
        title=title,
        video_path=video_path,
        thumbnail_path=thumbnail_path,
        flair_id=flair_id,
        nsfw=nsfw,
        spoiler=spoiler,
        send_replies=send_replies,
    )
    if not isinstance(result, Submission):
        return {"error": "Failed to create video post", "success": False}
    return serialize_submission(result)


def submit_gallery_post(
    subreddit: str,
    title: str,
    images: list[dict[str, str]],
    flair_id: str | None = None,
    nsfw: bool = False,
    spoiler: bool = False,
    send_replies: bool = True,
) -> dict:
    """
    Submit a gallery post with multiple images to a subreddit.

    Creates a post containing multiple images that users can swipe through.
    Each image can have an optional caption. All images are hosted on Reddit.

    Args:
        subreddit: Target subreddit name (without r/ prefix)
        title: Post title (max 300 characters)
        images: List of image dictionaries, each containing:
            - image_path (required): Local file path to the image
            - caption (optional): Text caption for this image
            - outbound_url (optional): URL to link from this image
        flair_id: Optional flair template ID
        nsfw: Mark post as NSFW
        spoiler: Mark post as spoiler
        send_replies: Receive inbox notifications for replies

    Returns:
        Dictionary with created post details including gallery metadata

    Example:
        submit_gallery_post(
            subreddit="pics",
            title="My Vacation Photos",
            images=[
                {"image_path": "/path/to/photo1.jpg", "caption": "Day 1"},
                {"image_path": "/path/to/photo2.jpg", "caption": "Day 2"},
                {"image_path": "/path/to/photo3.jpg"}
            ]
        )

    Note:
        Maximum number of images per gallery varies by subreddit (typically 20).
        All images must exist at specified paths.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    submission = sub.submit_gallery(
        title=title,
        images=images,
        flair_id=flair_id,
        nsfw=nsfw,
        spoiler=spoiler,
        send_replies=send_replies,
    )
    return serialize_submission(submission)


def submit_poll_post(
    subreddit: str,
    title: str,
    selftext: str,
    options: list[str],
    duration: int = 3,
    flair_id: str | None = None,
    nsfw: bool = False,
    spoiler: bool = False,
    send_replies: bool = True,
) -> dict:
    """
    Submit a poll post to a subreddit.

    Creates a post with a poll that users can vote on. Polls have a fixed
    duration and automatically close after the specified time period.

    Args:
        subreddit: Target subreddit name (without r/ prefix)
        title: Post title (max 300 characters)
        selftext: Optional body text explaining the poll (markdown supported)
        options: List of poll options (minimum 2, maximum 6 options)
        duration: Poll duration in days (1-7 days, default: 3)
        flair_id: Optional flair template ID
        nsfw: Mark post as NSFW
        spoiler: Mark post as spoiler
        send_replies: Receive inbox notifications for replies

    Returns:
        Dictionary with created post details including poll options and duration

    Example:
        submit_poll_post(
            subreddit="polls",
            title="What's your favorite color?",
            selftext="Help me decide on a color scheme!",
            options=["Red", "Blue", "Green", "Yellow"],
            duration=7
        )

    Note:
        Poll results are visible immediately. Once submitted, polls cannot be
        edited or extended. Each user can vote only once.
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    submission = sub.submit_poll(
        title=title,
        selftext=selftext,
        options=options,
        duration=duration,
        flair_id=flair_id,
        nsfw=nsfw,
        spoiler=spoiler,
        send_replies=send_replies,
    )
    return serialize_submission(submission)


def register_media_tools(mcp: FastMCP) -> None:
    """Register media submission tools."""
    mcp.tool()(submit_image_post)
    mcp.tool()(submit_video_post)
    mcp.tool()(submit_gallery_post)
    mcp.tool()(submit_poll_post)
