# core/templatetags/currency_filters.py
"""
Custom template filters for currency formatting.
Respects the per-company `use_comma_separator` setting (injected via context_processors).
"""
from django import template
from decimal import Decimal, InvalidOperation

register = template.Library()


def _to_decimal(value):
    """Safely convert value to Decimal. Returns Decimal('0') on failure."""
    try:
        return Decimal(str(value))
    except (InvalidOperation, TypeError, ValueError):
        return Decimal('0')


@register.filter(name='currency')
def currency(value, decimal_places=2):
    """
    Format a number as a currency amount.
    Always returns a plain number string (no symbol).
    Uses comma separator.
    Usage: {{ amount|currency }} or {{ amount|currency:0 }}
    """
    try:
        dp = int(decimal_places)
    except (ValueError, TypeError):
        dp = 2
    amount = _to_decimal(value)
    formatted = f"{amount:,.{dp}f}"
    return formatted


@register.filter(name='currency_no_comma')
def currency_no_comma(value, decimal_places=2):
    """
    Format a number as a currency amount WITHOUT comma separator.
    Usage: {{ amount|currency_no_comma:2 }}
    """
    try:
        dp = int(decimal_places)
    except (ValueError, TypeError):
        dp = 2
    amount = _to_decimal(value)
    return f"{amount:.{dp}f}"


@register.simple_tag(takes_context=True)
def fmt_currency(context, value, decimal_places=2):
    """
    Context-aware currency formatter.
    Respects use_comma_separator from context.
    Usage: {% fmt_currency value %} or {% fmt_currency value 0 %}
    Returns a string like "1,250.00" or "1250.00"
    """
    use_comma = context.get('use_comma_separator', True)
    try:
        dp = int(decimal_places)
    except (ValueError, TypeError):
        dp = 2
    amount = _to_decimal(value)
    if use_comma:
        return f"{amount:,.{dp}f}"
    return f"{amount:.{dp}f}"


@register.simple_tag(takes_context=True)
def money(context, value, decimal_places=2):
    """
    Context-aware currency formatter that prepends the currency symbol.
    Usage: {% money value %} → "₦1,250.00"
    """
    symbol = context.get('currency_symbol', '₦')
    use_comma = context.get('use_comma_separator', True)
    try:
        dp = int(decimal_places)
    except (ValueError, TypeError):
        dp = 2
    amount = _to_decimal(value)
    if use_comma:
        return f"{symbol}{amount:,.{dp}f}"
    return f"{symbol}{amount:.{dp}f}"
