# formatting.py — locale-aware number formatting and parsing
#
# SPDX-License-Identifier: GPL-3.0-or-later

import locale
import math

MINUS = "−"


def number(value, digits=2):
    text = locale.format_string(f"%.{digits}f", abs(value), grouping=True)
    return (MINUS + text) if value < 0 and text.strip("0.,   ") else text


def price(value):
    if value is None:
        return "—"
    return number(value, 2 if abs(value) >= 1 else 4)


def money(value, currency, digits=2):
    if value is None:
        return "—"
    return f"{number(value, digits)} {currency}"


def signed_money(value, currency, digits=2):
    if value is None:
        return "—"
    sign = "+" if value > 0 else ""
    return f"{sign}{number(value, digits)} {currency}"


def percent(value, signed=True):
    if value is None:
        return "—"
    sign = "+" if signed and value > 0 else ""
    return f"{sign}{number(value, 2)} %"


def plain(value, max_digits=4):
    """A number with up to max_digits decimals and no trailing zeros, no grouping
    (suitable for pre-filling an entry the user will edit)."""
    text = locale.format_string(f"%.{max_digits}f", value, grouping=False)
    point = locale.localeconv()["decimal_point"]
    if point in text:
        text = text.rstrip("0").rstrip(point)
    return text


def shares(value):
    if value == int(value):
        return number(value, 0)
    text = number(value, 4)
    point = locale.localeconv()["decimal_point"]
    return text.rstrip("0").rstrip(point)


def parse_decimal(text):
    """Parse a user-typed positive number; accepts "1 234,5", "1,234.5", "12.5".
    Returns None when the text is not a valid non-negative number."""
    t = (text or "").strip()
    for ch in (" ", " ", " ", "'"):
        t = t.replace(ch, "")
    if not t:
        return None
    if "," in t and "." in t:
        # whichever separator comes last is the decimal point
        if t.rfind(",") > t.rfind("."):
            t = t.replace(".", "").replace(",", ".")
        else:
            t = t.replace(",", "")
    elif "," in t:
        t = t.replace(",", ".")
    try:
        value = float(t)
    except ValueError:
        return None
    if not math.isfinite(value) or value < 0:
        return None
    return value


def direction(value):
    """'positive', 'negative' or None — used as a CSS class."""
    if value is None or abs(value) < 1e-9:
        return None
    return "positive" if value > 0 else "negative"


def clock(unix_time):
    """'22:14' for today, '1 Nov 22:14' for earlier days, in local time."""
    import time
    if unix_time is None:
        return "—"
    t = time.localtime(unix_time)
    if time.strftime("%Y%m%d", t) == time.strftime("%Y%m%d"):
        return time.strftime("%H:%M", t)
    return f"{t.tm_mday} {time.strftime('%b %H:%M', t)}"
