"""Чистая логика: суммы, даты, расчёт остатков. Без Telegram и БД — легко тестировать."""
from __future__ import annotations

import calendar
import math
import re
from datetime import date, timedelta

KINDS = {
    "credit": ("💳", "Кредит"),
    "i_owe": ("🔴", "Я должен"),
    "owed_me": ("🟢", "Мне должны"),
    "rent": ("🏠", "Аренда"),
    "sub": ("🔁", "Подписка"),
}
DEBT_KINDS = {"credit", "i_owe", "owed_me"}      # есть остаток, который уменьшается
OUTGOING = {"credit", "i_owe", "rent", "sub"}    # деньги уходят от меня
PERIODS = {"month": "ежемесячно", "week": "еженедельно", "year": "ежегодно"}
CURRENCIES = {"UZS": "сум", "USD": "$", "EUR": "€", "RUB": "₽"}


def kind_label(kind: str) -> str:
    emoji, name = KINDS[kind]
    return f"{emoji} {name}"


# ---------- суммы ----------

_SUFFIX = {"k": 1e3, "к": 1e3, "тыс": 1e3, "m": 1e6, "м": 1e6, "млн": 1e6}


def parse_amount(text: str) -> float | None:
    """'1 500 000', '1,5 млн', '500к', '99.99', '1.500.000' -> число. None если не распознано или <= 0."""
    t = text.strip().lower().replace(" ", " ")
    t = re.sub(r"(сум|sum|uzs|usd|eur|rub|\$|€|₽)", "", t).strip()
    m = re.fullmatch(r"([\d\s.,]+?)\s*(k|к|тыс|m|м|млн)?\.?", t)
    if not m:
        return None
    num, suf = m.group(1).replace(" ", ""), m.group(2)
    if not num or not any(ch.isdigit() for ch in num):
        return None
    commas = num.count(",")
    if commas > 1 or (commas == 1 and "." not in num and not suf and len(num.split(",")[1]) == 3):
        num = num.replace(",", "")           # 1,500,000 / 1,500
    else:
        num = num.replace(",", ".")          # 1,5
    if num.count(".") > 1:
        num = num.replace(".", "")           # 1.500.000
    try:
        v = float(num)
    except ValueError:
        return None
    if suf:
        v *= _SUFFIX[suf]
    v = round(v, 2)
    return v if v > 0 else None


def fmt_money(v: float | None, cur: str) -> str:
    if v is None:
        return "—"
    if float(v).is_integer():
        s = f"{int(v):,}"
    else:
        s = f"{v:,.2f}".rstrip("0").rstrip(".")
    return f"{s.replace(',', ' ')} {CURRENCIES.get(cur, cur)}"


# ---------- даты ----------

def clamp_day(y: int, m: int, d: int) -> date:
    return date(y, m, min(d, calendar.monthrange(y, m)[1]))


def add_months(d: date, n: int, anchor: int | None = None) -> date:
    """Сдвиг на n месяцев с «якорным» днём: 31.01 -> 28.02 -> 31.03 (а не 28.03)."""
    m0 = d.month - 1 + n
    return clamp_day(d.year + m0 // 12, m0 % 12 + 1, anchor or d.day)


def add_period(d: date, period: str, anchor: int | None = None) -> date:
    if period == "week":
        return d + timedelta(days=7)
    if period == "month":
        return add_months(d, 1, anchor)
    if period == "year":
        return add_months(d, 12, anchor)
    raise ValueError(period)


def parse_due(text: str, today: date) -> date | None:
    """'15' -> ближайшее 15-е (сегодня включительно); '15.12' -> ближайшее 15.12; '15.12.2026'; 'сегодня'/'завтра'."""
    t = text.strip().lower()
    if t in ("сегодня", "today"):
        return today
    if t in ("завтра", "tomorrow"):
        return today + timedelta(days=1)
    m = re.fullmatch(r"(\d{1,2})", t)
    if m:
        d = int(m.group(1))
        if not 1 <= d <= 31:
            return None
        c = clamp_day(today.year, today.month, d)
        return c if c >= today else add_months(c, 1, d)
    m = re.fullmatch(r"(\d{1,2})[./-](\d{1,2})(?:[./-](\d{2,4}))?", t)
    if m:
        d, mo, y = int(m.group(1)), int(m.group(2)), m.group(3)
        try:
            if y:
                yy = int(y)
                return date(yy + 2000 if yy < 100 else yy, mo, d)
            c = date(today.year, mo, d)
            return c if c >= today else date(today.year + 1, mo, d)
        except ValueError:
            return None
    return None


def due_anchor(text: str, d: date) -> int:
    """Якорный день: если ввели просто «31», помним 31 (в коротких месяцах — последний день)."""
    t = text.strip()
    return int(t) if t.isdigit() and 1 <= int(t) <= 31 else d.day


def due_label(due: date, today: date) -> str:
    delta = (due - today).days
    if delta == 0:
        return "сегодня"
    if delta == 1:
        return "завтра"
    if delta > 1:
        return f"через {delta} дн."
    return f"просрочено на {-delta} дн."


def should_remind(next_due: str | None, remind_before: int, today: date) -> bool:
    """Напоминаем: за N дней, в день платежа и каждый день, пока просрочено."""
    if not next_due:
        return False
    delta = (date.fromisoformat(next_due) - today).days
    return delta <= 0 or delta == remind_before


# ---------- расчёты ----------

def monthly_equiv(amount: float | None, period: str | None) -> float:
    if not amount or not period:
        return 0.0
    return {"month": amount, "week": amount * 52 / 12, "year": amount / 12}[period]


def payments_left(balance: float | None, amount: float | None) -> int | None:
    if not balance or not amount:
        return None
    return math.ceil(round(balance / amount, 6))


def estimate_end(next_due: date, period: str, anchor: int | None, n: int) -> date:
    d = next_due
    for _ in range(max(n - 1, 0)):
        d = add_period(d, period, anchor)
    return d


def period_left(ob) -> float | None:
    """Сколько ещё внести в счёт текущего платежа (с учётом внесённого заранее)."""
    if not ob["amount"]:
        return None
    left = ob["amount"] - (ob["period_paid"] or 0)
    if ob["kind"] in DEBT_KINDS and ob["balance"] is not None:
        left = min(left, ob["balance"])
    return round(max(left, 0.0), 2)


def apply_payment(ob: dict, amount: float) -> tuple[dict, bool, bool]:
    """Возвращает (обновления для obligations, закрыто_полностью, дата_сдвинута).

    - для долгов/кредитов уменьшает остаток; при 0 — закрывает (в архив);
    - внесённое копится в period_paid; когда набралась сумма обычного платежа
      (одним платежом или несколькими, заранее или в срок) — дата сдвигается на следующий период.
    """
    upd: dict = {}
    closed = advanced = False
    if ob["kind"] in DEBT_KINDS and ob.get("balance") is not None:
        nb = max(0.0, round(ob["balance"] - amount, 2))
        upd["balance"] = nb
        if nb <= 0:
            upd["active"] = 0
            closed = True
    if closed:
        upd["period_paid"] = 0
    elif ob.get("period") and ob.get("next_due"):
        paid = round((ob.get("period_paid") or 0) + amount, 2)
        if not ob.get("amount") or paid >= ob["amount"] * 0.99:
            nd = add_period(date.fromisoformat(ob["next_due"]), ob["period"], ob.get("due_day"))
            upd["next_due"] = nd.isoformat()
            paid = 0
            advanced = True
        upd["period_paid"] = paid
    return upd, closed, advanced
