"""
Custom template filters for surveys app
"""

from django import template

register = template.Library()


@register.filter
def split(value, separator=","):
    """
    Split a string by the given separator.

    Usage: {{ "a,b,c"|split:"," }}
    Returns: ['a', 'b', 'c']
    """
    if not value:
        return []
    return value.split(separator)


@register.filter
def get_item(dictionary, key):
    """
    Get an item from a dictionary by key.

    Usage: {{ my_dict|get_item:"key_name" }}
    Usage: {{ my_dict|get_item:variable_key }}
    """
    if dictionary is None:
        return None
    try:
        return dictionary.get(key)
    except (AttributeError, KeyError, TypeError):
        return None


@register.filter
def mul(value, arg):
    """
    Multiply a value by a given number.

    Usage: {{ value|mul:2 }}
    """
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter
def get_arabic_choice(choices_json, choice_value):
    """
    Look up the Arabic label (label_ar) from a question's choices_json
    by matching the English label to the stored choice_value.

    Usage: {{ question.choices_json|get_arabic_choice:response.choice_value }}
    """
    if not choices_json or not choice_value:
        return ""
    try:
        for choice in choices_json:
            if choice.get("label") == choice_value:
                return choice.get("label_ar", "")
    except (AttributeError, TypeError):
        pass
    return ""
