from django import template
from decimal import Decimal, InvalidOperation

register = template.Library()

@register.filter
def div(value, divisor):
    """
    Divides the value by the divisor.
    Returns 0 if divisor is 0 or None, or if value is None.
    """
    try:
        if not value or not divisor:
            return 0
        
        # Convert to Decimal for precise calculation
        value_decimal = Decimal(str(value))
        divisor_decimal = Decimal(str(divisor))
        
        if divisor_decimal == 0:
            return 0
            
        result = value_decimal / divisor_decimal
        return result
    except (ValueError, InvalidOperation, TypeError):
        return 0

@register.filter
def multiply(value, multiplier):
    """
    Multiplies the value by the multiplier.
    """
    try:
        if not value or not multiplier:
            return 0
        
        value_decimal = Decimal(str(value))
        multiplier_decimal = Decimal(str(multiplier))
        
        result = value_decimal * multiplier_decimal
        return result
    except (ValueError, InvalidOperation, TypeError):
        return 0

@register.filter
def percentage(value, total):
    """
    Calculates percentage of value from total.
    """
    try:
        if not value or not total:
            return 0
        
        value_decimal = Decimal(str(value))
        total_decimal = Decimal(str(total))
        
        if total_decimal == 0:
            return 0
            
        result = (value_decimal / total_decimal) * 100
        return result
    except (ValueError, InvalidOperation, TypeError):
        return 0

@register.filter
def abs(value):
    """
    Returns the absolute value of the number.
    """
    try:
        if value is None:
            return 0
        # Use the built-in abs function with a different name to avoid recursion
        import builtins
        return builtins.abs(float(value))
    except (ValueError, TypeError):
        return 0


@register.filter
def get_item(dictionary, key):
    """
    Gets an item from a dictionary by key.
    Usage: {{ my_dict|get_item:key }}
    """
    if dictionary is None:
        return None
    return dictionary.get(key)
