import os
import sys
import tempfile
from datetime import date

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import logic as L  # noqa: E402
from db import DB  # noqa: E402


def test_parse_amount():
    cases = {
        "1 500 000": 1_500_000, "1500000": 1_500_000, "1,5 млн": 1_500_000, "1.5m": 1_500_000,
        "500к": 500_000, "500 тыс": 500_000, "9.99": 9.99, "9,99": 9.99, "1,500,000": 1_500_000,
        "1.500.000": 1_500_000, "1,500": 1500, "$120": 120, "3 500 000 сум": 3_500_000,
    }
    for s, v in cases.items():
        assert L.parse_amount(s) == v, (s, L.parse_amount(s))
    for bad in ["", "abc", "0", "-5", "1..2x"]:
        assert L.parse_amount(bad) is None, bad


def test_fmt():
    assert L.fmt_money(1500000, "UZS") == "1 500 000 сум"
    assert L.fmt_money(9.9, "USD") == "9.9 $"


def test_dates():
    t = date(2026, 11, 29)
    assert L.parse_due("15", t) == date(2026, 12, 15)
    assert L.parse_due("29", t) == date(2026, 11, 29)
    assert L.parse_due("31", t) == date(2026, 11, 30)   # в ноябре 30 дней
    assert L.due_anchor("31", date(2026, 11, 30)) == 31
    assert L.parse_due("30", t) == date(2026, 11, 30)
    assert L.parse_due("01.01", t) == date(2027, 1, 1)
    assert L.parse_due("15.12.26", t) == date(2026, 12, 15)
    assert L.parse_due("завтра", t) == date(2026, 11, 30)
    assert L.parse_due("32", t) is None and L.parse_due("31.02", t) is None
    # якорный день: 31 -> 28/29 фев -> 31 мар
    d = date(2027, 1, 31)
    d = L.add_period(d, "month", 31); assert d == date(2027, 2, 28)
    d = L.add_period(d, "month", 31); assert d == date(2027, 3, 31)
    assert L.add_period(date(2026, 12, 1), "week") == date(2026, 12, 8)
    assert L.add_period(date(2028, 2, 29), "year", 29) == date(2029, 2, 28)


def test_remind():
    t = date(2026, 12, 1)
    assert L.should_remind("2026-12-04", 3, t)
    assert not L.should_remind("2026-12-03", 3, t)
    assert L.should_remind("2026-12-01", 3, t)
    assert L.should_remind("2026-11-20", 3, t)    # просрочено — каждый день
    assert not L.should_remind(None, 3, t)


def test_payment_logic():
    ob = dict(kind="credit", period_paid=0, balance=10_000_000, amount=3_000_000, period="month",
              next_due="2026-12-15", due_day=15)
    upd, closed, adv = L.apply_payment(ob, 3_000_000)
    assert upd == {"balance": 7_000_000, "next_due": "2027-01-15", "period_paid": 0} and adv and not closed
    upd, closed, adv = L.apply_payment(ob, 1_000_000)           # частично заранее
    assert upd == {"balance": 9_000_000, "period_paid": 1_000_000} and not adv
    ob2 = {**ob, **upd}
    assert L.period_left(ob2) == 2_000_000
    upd, _, adv = L.apply_payment(ob2, 2_000_000)               # добил остаток периода
    assert adv and upd["period_paid"] == 0 and upd["next_due"] == "2027-01-15"
    upd, closed, adv = L.apply_payment(ob, 12_000_000)          # переплата закрывает
    assert upd["balance"] == 0 and upd["active"] == 0 and closed
    sub = dict(kind="sub", period_paid=0, balance=None, amount=10, period="month", next_due="2026-12-05", due_day=5)
    upd, _, adv = L.apply_payment(sub, 10)
    assert upd == {"next_due": "2027-01-05", "period_paid": 0}
    assert L.payments_left(10_000_000, 3_000_000) == 4
    assert L.payments_left(9_000_000, 3_000_000) == 3
    assert L.estimate_end(date(2026, 12, 15), "month", 15, 4) == date(2027, 3, 15)
    assert round(L.monthly_equiv(120, "year"), 2) == 10


def test_db_payment_undo():
    with tempfile.TemporaryDirectory() as d:
        db = DB(os.path.join(d, "t.db"))
        oid = db.add_obligation(kind="credit", name="X", currency="UZS", balance=6, amount=3,
                                period="month", due_day=15, next_due="2026-12-15", remind_before=1)
        o = db.get(oid)
        upd, _, _ = L.apply_payment(dict(o), 3)
        p1 = db.record_payment(o, 3, "2026-12-15", upd)
        o = db.get(oid)
        upd, closed, _ = L.apply_payment(dict(o), 3)
        p2 = db.record_payment(o, 3, "2027-01-15", upd)
        assert closed and db.get(oid)["active"] == 0
        assert db.undo_payment(p1) is None            # не последний
        assert db.undo_payment(p2) == oid
        o = db.get(oid)
        assert o["active"] == 1 and o["balance"] == 3 and o["next_due"] == "2027-01-15"
        assert len(db.payments(oid)) == 1
