from django import template
from django.utils.formats import date_format

register = template.Library()

STATUS_TONES = {
    # Verde — saudável, concluído ou confirmado
    "active": "green",
    "low": "green",
    "healthy": "green",
    "up": "green",
    "paid": "green",
    "renewed": "green",
    "verified": "green",
    "resolved": "green",
    "closed": "gray",
    "done": "green",
    "sent": "green",
    "approved": "green",
    "delivered": "green",
    "created": "amber",
    "imported": "green",
    # Azul — em curso, informação ou processamento normal
    "in_progress": "blue",
    "normal": "blue",
    "development": "blue",
    "scheduled": "blue",
    "processing": "blue",
    "running": "blue",
    "transfer_in": "blue",
    "sending": "blue",
    "analysing": "blue",
    "importing": "blue",
    "provisioning": "blue",
    "migrating": "blue",
    "reopened": "blue",
    # Amarelo/laranja — atenção, espera ou proximidade
    "pending": "amber",
    "open": "amber",
    "todo": "amber",
    "high": "amber",
    "to_notify": "amber",
    "notified": "blue",
    "waiting_payment": "amber",
    "waiting_proof": "amber",
    "validating": "blue",
    "partial": "amber",
    "waiting_client": "amber",
    "waiting_internal": "amber",
    "waiting": "amber",
    "attention": "amber",
    "maintenance": "amber",
    "expiring": "amber",
    "review": "blue",
    "ready": "amber",
    "uploaded": "amber",
    "grace": "amber",
    "degraded": "orange",
    "acknowledged": "amber",
    "limited": "orange",
    "on_hold": "orange",
    "blocked": "red",
    # Vermelho — falha, vencido, incidente ou ação urgente
    "overdue": "red",
    "expired": "red",
    "failed": "red",
    "rejected": "red",
    "urgent": "red",
    "debt": "red",
    "incident": "red",
    "offline": "red",
    "down": "red",
    "critical": "red",
    "suspended": "red",
    # Cinzento — encerrado, cancelado, desconhecido ou histórico
    "cancelled": "gray",
    "archived": "gray",
    "inactive": "gray",
    "retired": "gray",
    "transferred": "gray",
    "unknown": "gray",
    "draft": "gray",
    "refunded": "gray",
    "rolled_back": "gray",
    "skipped": "gray",
    "paused": "gray",
    "suppressed": "amber",
    "client_direct": "violet",
    "complimentary": "violet",
    "special": "blue",
    "quote": "gray",
}


@register.filter
def status_tone(value):
    return STATUS_TONES.get(str(value or "").lower(), "gray")


@register.filter
def euro(value):
    try:
        return f"{value:,.2f} €".replace(",", "X").replace(".", ",").replace("X", ".")
    except (TypeError, ValueError):
        return "0,00 €"


@register.filter
def pt_date(value):
    if not value:
        return "—"
    return date_format(value, "d/m/Y")


@register.filter
def basename(value):
    return str(value).replace("\\", "/").split("/")[-1]
