"""Flair management tools for Reddit."""

from mcp.server.fastmcp import FastMCP

from reddit_mcp.reddit_client import get_reddit


def set_user_flair(
    subreddit: str,
    username: str,
    text: str = "",
    css_class: str = "",
    flair_template_id: str = "",
) -> dict:
    """Set a user's flair in a subreddit.

    Use this to assign custom flair to users. Can use a template or
    custom text/css.

    Args:
        subreddit: Subreddit name (without r/)
        username: Username (without u/)
        text: Flair text (if not using template)
        css_class: CSS class for styling (if not using template)
        flair_template_id: Template ID to use (overrides text/css_class)

    Returns:
        Success status and flair details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)

    if flair_template_id:
        sub.flair.set(username, flair_template_id=flair_template_id)
    else:
        sub.flair.set(username, text=text, css_class=css_class)

    return {
        "success": True,
        "subreddit": subreddit,
        "username": username,
        "action": "flair_set",
        "text": text,
    }


def delete_user_flair(subreddit: str, username: str) -> dict:
    """Remove a user's flair from a subreddit.

    Use this to clear a user's flair completely.

    Args:
        subreddit: Subreddit name (without r/)
        username: Username (without u/)

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    sub.flair.delete(username)
    return {
        "success": True,
        "subreddit": subreddit,
        "username": username,
        "action": "flair_deleted",
    }


def set_post_flair(
    post_id: str, text: str = "", css_class: str = "", flair_template_id: str = ""
) -> dict:
    """Set flair on a post.

    Use this to categorize posts with flair. Can use a template or
    custom text/css.

    Args:
        post_id: Post ID (with or without t3_ prefix)
        text: Flair text (if not using template)
        css_class: CSS class for styling (if not using template)
        flair_template_id: Template ID to use (overrides text/css_class)

    Returns:
        Success status and flair details
    """
    reddit = get_reddit()
    post_id = post_id.replace("t3_", "")
    submission = reddit.submission(id=post_id)

    if flair_template_id:
        submission.flair.select(flair_template_id)
    else:
        submission.mod.flair(text=text, css_class=css_class)

    return {
        "success": True,
        "post_id": f"t3_{post_id}",
        "action": "flair_set",
        "text": text,
    }


def get_flair_templates(subreddit: str, flair_type: str = "LINK_FLAIR") -> dict:
    """Get available flair templates in a subreddit.

    Use this to see all available flair options for posts or users.

    Args:
        subreddit: Subreddit name (without r/)
        flair_type: "LINK_FLAIR" for posts or "USER_FLAIR" for users

    Returns:
        List of available flair templates
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)
    source = (
        sub.flair.link_templates if flair_type == "LINK_FLAIR" else sub.flair.templates
    )
    templates = [
        {
            "id": template["id"],
            "text": template["text"],
            "css_class": template.get("css_class", ""),
            "text_editable": template.get("text_editable", False),
            "mod_only": template.get("mod_only", False),
        }
        for template in source
    ]

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


def create_flair_template(
    subreddit: str,
    text: str,
    css_class: str = "",
    text_editable: bool = False,
    mod_only: bool = False,
    flair_type: str = "LINK_FLAIR",
) -> dict:
    """Create a new flair template.

    Use this to add new flair options for posts or users.

    Args:
        subreddit: Subreddit name (without r/)
        text: Default flair text
        css_class: CSS class for styling
        text_editable: Allow users to edit the text
        mod_only: Only moderators can use this flair
        flair_type: "LINK_FLAIR" for posts or "USER_FLAIR" for users

    Returns:
        Success status and template details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)

    if flair_type == "LINK_FLAIR":
        sub.flair.link_templates.add(
            text=text,
            css_class=css_class,
            text_editable=text_editable,
            mod_only=mod_only,
        )
    else:
        sub.flair.templates.add(
            text=text,
            css_class=css_class,
            text_editable=text_editable,
            mod_only=mod_only,
        )

    return {
        "success": True,
        "subreddit": subreddit,
        "action": "flair_template_created",
        "flair_type": flair_type,
        "text": text,
    }


def delete_flair_template(
    subreddit: str, template_id: str, flair_type: str = "LINK_FLAIR"
) -> dict:
    """Delete a flair template.

    Use this to remove a flair option from the subreddit.

    Args:
        subreddit: Subreddit name (without r/)
        template_id: Template ID to delete
        flair_type: "LINK_FLAIR" for posts or "USER_FLAIR" for users

    Returns:
        Success status and action details
    """
    reddit = get_reddit()
    sub = reddit.subreddit(subreddit)

    if flair_type == "LINK_FLAIR":
        sub.flair.link_templates.delete(template_id)
    else:
        sub.flair.templates.delete(template_id)

    return {
        "success": True,
        "subreddit": subreddit,
        "action": "flair_template_deleted",
        "template_id": template_id,
    }


def register_flair_moderation_tools(mcp: FastMCP) -> None:
    """Register flair management tools."""
    mcp.tool()(set_user_flair)
    mcp.tool()(delete_user_flair)
    mcp.tool()(set_post_flair)
    mcp.tool()(get_flair_templates)
    mcp.tool()(create_flair_template)
    mcp.tool()(delete_flair_template)
