"""Locale-independent formatting (TZ 2.4.2): numbers, money, percents, dates, plurals.

Does not use the OS locale, ``strftime`` or Babel/CLDR. Tables live in ``snapfile_render/locales/*.json``
and are shared with the frontend. Rounding is ROUND_HALF_UP everywhere.
"""

from __future__ import annotations

import json
import re
from datetime import date, datetime, timedelta, timezone
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from functools import lru_cache
from pathlib import Path
from typing import Any

_LOCALES_DIR = Path(__file__).parent / "locales"


@lru_cache(maxsize=8)
def locale_table(code: str) -> dict[str, Any]:
    base = str(code or "en").replace("_", "-").split("-")[0].lower()
    path = _LOCALES_DIR / f"{base}.json"
    if not base.isalnum() or not path.exists():
        path = _LOCALES_DIR / "en.json"
    return json.loads(path.read_text(encoding="utf-8"))


def to_decimal(value: Any) -> Decimal | None:
    """Convert JSON-ish numeric input (int/float/Decimal/numeric string) to Decimal."""
    if isinstance(value, bool) or value is None:
        return None
    if isinstance(value, Decimal):
        return value
    if isinstance(value, int):
        return Decimal(value)
    if isinstance(value, float):
        return Decimal(repr(value))
    if isinstance(value, str):
        s = value.strip().replace(" ", "").replace(" ", "")
        if not s:
            return None
        if s.count(",") == 1 and "." not in s:
            s = s.replace(",", ".")
        try:
            return Decimal(s)
        except InvalidOperation:
            return None
    return None


def _group(int_part: str, sep: str) -> str:
    if len(int_part) <= 3:
        return int_part
    out: list[str] = []
    while len(int_part) > 3:
        out.append(int_part[-3:])
        int_part = int_part[:-3]
    out.append(int_part)
    return sep.join(reversed(out))


def format_number(
    value: Decimal,
    locale: str,
    decimals: int | None = None,
    *,
    grouping: bool = True,
    sign: str = "auto",
) -> str:
    table = locale_table(locale)
    if decimals is not None:
        decimals = max(0, min(10, int(decimals)))
        q = Decimal(1).scaleb(-decimals)
        value = value.quantize(q, rounding=ROUND_HALF_UP)
        text = f"{abs(value):.{decimals}f}"
    else:
        normalized = abs(value).normalize()
        text = format(normalized, "f")
        if "." in text:
            text = text.rstrip("0").rstrip(".")
    int_part, _, frac = text.partition(".")
    if grouping:
        int_part = _group(int_part, table["group"])
    out = int_part + (table["decimal"] + frac if frac else "")
    negative = value < 0 and any(ch not in "0.," for ch in text)
    if negative:
        return "-" + out
    if sign == "always" and value > 0:
        return "+" + out
    return out


def format_plain_number(value: Decimal, locale: str) -> str:
    """Default output of a number without filters: locale decimal separator, no grouping."""
    return format_number(value, locale, None, grouping=False)


def format_percent(value: Decimal, locale: str, decimals: int | None = 0) -> str:
    table = locale_table(locale)
    return format_number(value * 100, locale, decimals) + table["percentSuffix"]


def format_money(
    value: Any, locale: str, currency: str | None = None, decimals: int | None = 2, display: str = "symbol"
) -> str | None:
    amount: Decimal | None
    if isinstance(value, dict):
        amount = to_decimal(value.get("amount"))
        currency = currency or value.get("currency")
    else:
        amount = to_decimal(value)
    if amount is None:
        return None
    table = locale_table(locale)
    currency = (currency or "").upper()
    number = format_number(amount, locale, 2 if decimals is None else decimals)
    if display == "none" or not currency:
        return number
    symbol = table["currencySymbols"].get(currency, currency) if display == "symbol" else currency
    negative = number.startswith("-")
    if negative:
        number = number[1:]
    if display == "code":
        out = f"{number} {symbol}" if locale == "ru" else f"{symbol} {number}"
    else:
        out = table["moneyPattern"].replace("{amount}", number).replace("{symbol}", symbol)
    return "-" + out if negative else out


_ISO_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$")


def parse_date(value: Any) -> datetime | None:
    if isinstance(value, datetime):
        return value
    if isinstance(value, date):
        return datetime(value.year, value.month, value.day)
    if not isinstance(value, str):
        return None
    m = _ISO_RE.match(value.strip())
    if not m:
        return None
    y, mo, d, hh, mi, ss, tz = m.groups()
    try:
        dt = datetime(int(y), int(mo), int(d), int(hh or 0), int(mi or 0), int(ss or 0))
    except ValueError:
        return None
    if tz:
        if tz == "Z":
            offset = timedelta(0)
        else:
            sign = -1 if tz[0] == "-" else 1
            digits = tz[1:].replace(":", "")
            offset = sign * timedelta(hours=int(digits[:2]), minutes=int(digits[2:]))
        dt = dt.replace(tzinfo=timezone(offset))
    return dt


_DATE_TOKEN_RE = re.compile(r"'[^']*'|yyyy|yy|MMMM|MMM|MM|M|LLLL|dd|d|HH|H|mm|ss")


def format_date(value: datetime, locale: str, pattern: str | None = None, tz_offset_minutes: int | None = None) -> str:
    table = locale_table(locale)
    if tz_offset_minutes is not None and value.tzinfo is not None:
        value = value.astimezone(timezone(timedelta(minutes=tz_offset_minutes)))
    pattern = pattern or table["datePattern"]

    def repl(m: re.Match[str]) -> str:
        tok = m.group()
        if tok.startswith("'"):
            return tok[1:-1]
        return {
            "yyyy": f"{value.year:04d}",
            "yy": f"{value.year % 100:02d}",
            "MMMM": table["months"][value.month - 1],
            "LLLL": table["monthsStandalone"][value.month - 1],
            "MMM": table["monthsShort"][value.month - 1],
            "MM": f"{value.month:02d}",
            "M": str(value.month),
            "dd": f"{value.day:02d}",
            "d": str(value.day),
            "HH": f"{value.hour:02d}",
            "H": str(value.hour),
            "mm": f"{value.minute:02d}",
            "ss": f"{value.second:02d}",
        }[tok]

    return _DATE_TOKEN_RE.sub(repl, pattern)


def plural_index(n: Decimal, locale: str) -> int:
    """0=one, 1=few, 2=many (ru); en uses 0=one, 1=other."""
    if n != n.to_integral_value():
        return 1
    i = abs(int(n))
    if locale == "ru":
        if i % 10 == 1 and i % 100 != 11:
            return 0
        if 2 <= i % 10 <= 4 and not 12 <= i % 100 <= 14:
            return 1
        return 2
    return 0 if i == 1 else 1


_ROMAN = [
    (1000, "M"),
    (900, "CM"),
    (500, "D"),
    (400, "CD"),
    (100, "C"),
    (90, "XC"),
    (50, "L"),
    (40, "XL"),
    (10, "X"),
    (9, "IX"),
    (5, "V"),
    (4, "IV"),
    (1, "I"),
]


def roman(n: int) -> str:
    if n <= 0 or n >= 4000:
        return str(n)
    out: list[str] = []
    for value, sym in _ROMAN:
        while n >= value:
            out.append(sym)
            n -= value
    return "".join(out)


def title_case(text: str) -> str:
    """Shared title-case rule (TZ 2.6.5 step 1): uppercase a letter that starts the string or follows
    whitespace or one of ``- – — / ( « " '``; lowercase all other letters."""
    out: list[str] = []
    boundary = True
    for ch in text:
        if boundary and ch.isalpha():
            out.append(ch.upper())
            boundary = False
        else:
            out.append(ch.lower())
            boundary = ch.isspace() or ch in "-–—/(«\"'"
    return "".join(out)


def apply_phone_mask(digits_source: str, mask: str) -> str:
    digits = [c for c in digits_source if c.isdigit()]
    if mask.startswith("+7") and len(digits) == 11 and digits[0] in "78":
        digits = digits[1:]
    out: list[str] = []
    di = 0
    for ch in mask:
        if ch == "#":
            if di < len(digits):
                out.append(digits[di])
                di += 1
            else:
                break
        else:
            out.append(ch)
    return "".join(out)
