# social/templatetags/social_filters.py
import json
from django import template

register = template.Library()

@register.filter
def get_item(dictionary, key):
    """
    Get an item from a dictionary using a variable key.
    Usage: {{ mydict|get_item:key }}
    """
    if isinstance(dictionary, dict):
        return dictionary.get(key)
    return None

@register.filter
def pprint(value):
    """
    Pretty print JSON/dict values.
    Usage: {{ data|pprint }}
    """
    if isinstance(value, (dict, list)):
        return json.dumps(value, indent=2, ensure_ascii=False)
    return str(value)

@register.filter
def percentage(value):
    """
    Convert a decimal to a percentage string.
    Usage: {{ 0.95|percentage }} -> 95%
    """
    try:
        if value is None:
            return 'N/A'
        # Convert to float if it's a string
        float_value = float(value)
        # Convert to percentage
        percentage = float_value * 100
        return f"{percentage:.0f}%"
    except (ValueError, TypeError):
        return str(value)
