"""
Custom template filters for social app
"""
from django import template

register = template.Library()


@register.filter
def multiply(value, arg):
    """Multiply value by arg"""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter
def add(value, arg):
    """Add arg to value"""
    try:
        return float(value) + float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter
def get_sentiment_emoji(sentiment):
    """Get emoji for sentiment classification"""
    emoji_map = {
        'positive': '😊',
        'negative': '😞',
        'neutral': '😐'
    }
    return emoji_map.get(sentiment.lower(), '😐')


@register.filter
def lookup(dictionary, key):
    """
    Lookup a key in a dictionary.
    
    Usage: {{ stats|lookup:platform_code }}
    """
    if dictionary is None:
        return 0
    return dictionary.get(key, 0)


@register.filter
def get_item(dictionary, key):
    """
    Get an item from a dictionary using dot notation.
    
    Usage: {{ sentiment_distribution|get_item:positive|get_item:count }}
    """
    if dictionary is None:
        return None
    return dictionary.get(key, None)


@register.filter
def get_sentiment(comment):
    """
    Get sentiment classification from ai_analysis.
    
    Usage: {{ comment|get_sentiment }}
    """
    if not hasattr(comment, 'ai_analysis') or not comment.ai_analysis:
        return None
    return comment.ai_analysis.get('sentiment', {}).get('classification', {}).get('en')


@register.filter
def get_sentiment_count(sentiment_list, sentiment_type):
    """
    Get count for a specific sentiment from a list of sentiment dictionaries.
    
    Usage: {{ sentiment_distribution|get_sentiment_count:'positive' }}
    
    Args:
        sentiment_list: List of sentiment dictionaries with 'sentiment' and 'count' keys
        sentiment_type: String value to match (e.g., 'positive', 'negative', 'neutral')
    
    Returns:
        Count of items matching the sentiment_type, or 0 if not found
    """
    if not sentiment_list:
        return 0
    for item in sentiment_list:
        if isinstance(item, dict) and item.get('sentiment') == sentiment_type:
            return item.get('count', 0)
    return 0
