from django import template

register = template.Library()


@register.filter(name="multiply")
def multiply(value, arg):
    """Multiply two numbers in Django templates"""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter(name="add_float")
def add_float(value, arg):
    """Add two numbers in Django templates"""
    try:
        return float(value) + float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter(name="sum_addon_prices")
def sum_addon_prices(addons):
    """Sum the prices of addons"""
    try:
        return sum(addon.price for addon in addons)
    except (AttributeError, TypeError):
        return 0


@register.filter(name="calculate_addon_total")
def calculate_addon_total(addons, units):
    """Calculate total cost of addons based on their type and units"""
    try:
        total = 0
        for addon in addons:
            if addon.addon_type == "Unit Rate":
                total += float(addon.price) * float(units)
            else:  # Base Fee or other types
                total += float(addon.price)
        return total
    except (AttributeError, TypeError, ValueError):
        return 0
