# (c) cavaliba.com - data - humanize.py

"""
Human-friendly display of raw values, for dataview columns (`humanize:` option).

Pure functions: number in -> text out (dates in -> text out). Byte and SI symbols are
not translated; time words are (gettext). Callers keep the raw value for sorting,
colour rules and export.

Method inventory: parse_spec, humanize, number_text, bytes_text, si_text,
percent_text, duration_text, relative_text, day_text.
"""

from datetime import timedelta

from django.utils import timezone
from django.utils.translation import gettext as _
from django.utils.translation import ngettext

# kind -> (needs, valid args); needs: "number" or "date"
KINDS = {
    "bytes": "number",
    "ibytes": "number",
    "si": "number",
    "percent": "number",
    "duration": "number",
    "relative": "date",
    "day": "date",
}

BYTES_UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]
IBYTES_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]
SI_PREFIXES = ["", "k", "M", "G", "T", "P", "E"]

# duration input units (seconds per unit)
DURATION_UNITS = {"s": 1, "min": 60, "h": 3600, "d": 86400}

# precision word -> duration parts shown; one letter = single unit, spelled out
PRECISIONS = {
    "d": ("d",),
    "dh": ("d", "h"),
    "dhm": ("d", "h", "m"),
    "dhms": ("d", "h", "m", "s"),
    "h": ("h",),
    "m": ("m",),
    "s": ("s",),
}
DEFAULT_PRECISION = "dh"  # relative dates
DURATION_PRECISION = "dhm"  # durations

_SECONDS = {"d": 86400, "h": 3600, "m": 60, "s": 1}
_COMPACT = {"d": "d", "h": "h", "m": "min", "s": "s"}


def parse_spec(spec):
    """Parse "kind [arg] [arg]" into (kind, unit_in, precision) or raise ValueError
    with a readable reason. unit_in / precision are None when not applicable."""

    parts = str(spec or "").split()
    if not parts or parts[0] not in KINDS:
        raise ValueError(f"unknown humanize kind '{spec}'")
    kind, args = parts[0], parts[1:]
    unit_in, precision = None, None
    if kind in ("bytes", "ibytes"):
        units = BYTES_UNITS if kind == "bytes" else IBYTES_UNITS
        if len(args) > 1 or (args and args[0] not in units):
            raise ValueError(f"humanize {kind}: unit must be one of {' '.join(units)}")
        unit_in = args[0] if args else "B"
    elif kind == "duration":
        # "duration [unit] [precision]": a first word that is a unit (s min h d) is the
        # stored unit, so "duration d" = stored in days; "duration s d" = days precision
        for arg in args:
            if arg in DURATION_UNITS and unit_in is None:
                unit_in = arg
            elif arg in PRECISIONS and precision is None:
                precision = arg
            else:
                raise ValueError(f"humanize duration: bad argument '{arg}'")
        unit_in = unit_in or "s"
        precision = precision or DURATION_PRECISION
    elif kind == "relative":
        if len(args) > 1 or (args and args[0] not in PRECISIONS):
            raise ValueError(f"humanize relative: precision must be one of {' '.join(PRECISIONS)}")
        precision = args[0] if args else DEFAULT_PRECISION
    elif args:
        raise ValueError(f"humanize {kind}: takes no argument")
    return kind, unit_in, precision


def number_text(value, format_spec=None):
    """Number display: format_spec if given, else one decimal with ".0" dropped."""

    if format_spec is not None:
        try:
            return format(value, format_spec)
        except (ValueError, TypeError):
            pass
    text = f"{value:.1f}"
    return text[:-2] if text.endswith(".0") else text


def _scaled(value, base, symbols, start=0, format_spec=None):
    """value (in symbols[start]) scaled to the largest symbol keeping |value| >= 1."""

    index = start
    while abs(value) >= base and index < len(symbols) - 1:
        value /= base
        index += 1
    while abs(value) < 1 and value != 0 and index > 0:
        value *= base
        index -= 1
    return number_text(value, format_spec), symbols[index]


def bytes_text(value, unit_in="B", format_spec=None, binary=False):
    """1536000000 -> "1.5 GB" (base 1000), binary -> "1.4 GiB" (base 1024)."""

    symbols = IBYTES_UNITS if binary else BYTES_UNITS
    number, symbol = _scaled(value, 1024 if binary else 1000, symbols, symbols.index(unit_in),
                             format_spec)  # fmt: skip
    return f"{number} {symbol}"


def si_text(value, unit="", format_spec=None):
    """1234567 -> "1.2 M"; with unit "W" -> "1.2 MW"."""

    number, prefix = _scaled(value, 1000, SI_PREFIXES, 0, format_spec)
    return f"{number} {prefix}{unit.strip()}".rstrip()


def percent_text(value, format_spec=None):
    """Ratio 0.456 -> "45.6%"."""

    return number_text(value * 100, format_spec) + "%"


def _parts(seconds, precision):
    """[(unit, count), ...] for the units of precision, rounded down."""

    reply = []
    remaining = int(seconds)
    for unit in PRECISIONS[precision]:
        count, remaining = divmod(remaining, _SECONDS[unit])
        reply.append((unit, count))
    return reply


def _single(unit, count):
    """Spelled-out single unit: "10 days", "1 hour", "14600 min", "876000 sec"."""

    if unit == "d":
        return ngettext("%(n)d day", "%(n)d days", count) % {"n": count}
    if unit == "h":
        return ngettext("%(n)d hour", "%(n)d hours", count) % {"n": count}
    if unit == "m":
        return _("%(n)d min") % {"n": count}
    return _("%(n)d sec") % {"n": count}


def duration_text(seconds, precision=DURATION_PRECISION):
    """Seconds -> "10d 3h 20min" (multi-unit, zero parts dropped) or "567 hours"
    (single unit). Negative values use their absolute value."""

    parts = _parts(abs(seconds), precision)
    if len(parts) == 1:
        return _single(*parts[0])
    shown = [f"{count}{_COMPACT[unit]}" for unit, count in parts if count]
    return " ".join(shown) or f"0{_COMPACT[parts[-1][0]]}"


def relative_text(dt, precision=DEFAULT_PRECISION, now=None):
    """Aware datetime -> "10d 3h ago" / "in 34 days" / "now"."""

    now = now or timezone.now()
    seconds = (dt - now).total_seconds()
    smallest = _SECONDS[PRECISIONS[precision][-1]]
    if abs(seconds) < smallest:
        return _("now")
    text = duration_text(seconds, precision)
    if seconds > 0:
        return _("in %(duration)s") % {"duration": text}
    return _("%(duration)s ago") % {"duration": text}


def day_text(dt, now=None):
    """Aware datetime -> "today" / "yesterday" / "tomorrow", else "YYYY-MM-DD"
    (active timezone)."""

    day = timezone.localtime(dt).date()
    today = timezone.localtime(now or timezone.now()).date()
    if day == today:
        return _("today")
    if day == today - timedelta(days=1):
        return _("yesterday")
    if day == today + timedelta(days=1):
        return _("tomorrow")
    return day.isoformat()


def humanize(parsed, value, format_spec=None, unit="", now=None):
    """Display text for a raw value (number, or aware datetime for date kinds)
    under a parse_spec() result; None if the value doesn't fit the kind."""

    kind, unit_in, precision = parsed
    if KINDS[kind] == "date":
        if value is None:
            return None
        return relative_text(value, precision, now) if kind == "relative" else day_text(value, now)
    if value is None:
        return None
    if kind == "bytes":
        return bytes_text(value, unit_in, format_spec)
    if kind == "ibytes":
        return bytes_text(value, unit_in, format_spec, binary=True)
    if kind == "si":
        return si_text(value, unit, format_spec)
    if kind == "percent":
        return percent_text(value, format_spec)
    return duration_text(value * DURATION_UNITS[unit_in], precision)
