"""Compact relative time for CMS tables: 1m ago rather than 1 minute ago."""
from django import template
from django.utils import timezone

register = template.Library()


@register.filter
def short_ago(when):
    """
    Return a compact age string: 0m, 45m, 3h, 2d, 5w.

    Mirrors _short_ago() used by the Fleet page so both read the same way.
    Returns an empty string when there is no timestamp.
    """
    if not when:
        return ''
    seconds = (timezone.now() - when).total_seconds()
    if seconds < 0:
        seconds = 0
    minutes = int(seconds // 60)
    if minutes < 60:
        return f'{minutes}m'
    hours = minutes // 60
    if hours < 24:
        return f'{hours}h'
    days = hours // 24
    if days < 7:
        return f'{days}d'
    return f'{days // 7}w'


@register.filter
def short_duration(delta):
    """
    A timedelta as '2m', '3h 40m', '1d 21h'.

    Rendering a timedelta straight prints '1 day, 21:54:41.865252', which is
    accurate and unreadable. Same units as short_ago so the page reads one way.
    """
    if delta is None:
        return ''
    seconds = int(getattr(delta, 'total_seconds', lambda: 0)())
    if seconds < 0:
        seconds = 0
    minutes, hours = seconds // 60, seconds // 3600
    days = hours // 24
    if minutes < 60:
        return f'{minutes}m'
    if hours < 24:
        rem = minutes % 60
        return f'{hours}h {rem}m' if rem else f'{hours}h'
    rem = hours % 24
    return f'{days}d {rem}h' if rem else f'{days}d'
