"""SimpleFinCalc independent reference: Python 3, standard library only.
Hypothetical fixed-rate monthly loan. No fees, daily accrual or tax.
Run: python reference-loan.py
"""
from decimal import Decimal, ROUND_HALF_UP, getcontext
getcontext().prec = 40
def cents(n):
    return n.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
def schedule(extra='0', lump='0'):
    balance = Decimal('12000')
    rate = Decimal('0.06') / 12
    months = 36
    regular = cents(balance * rate / (1 - (1 + rate) ** -months))
    total_interest = total_paid = Decimal('0')
    for month in range(1, months + 1):
        interest = cents(balance * rate)
        due = cents(balance + interest)
        scheduled = due if month == months else min(regular, due)
        additional = min(due - scheduled, Decimal(extra) + (Decimal(lump) if month == 6 else 0))
        paid = cents(scheduled + additional)
        balance = cents(balance + interest - paid)
        total_interest += interest
        total_paid += paid
        if balance == 0:
            break
    assert total_paid == Decimal('12000') + total_interest
    return regular, month, total_interest, total_paid
if __name__ == '__main__':
    expected=[('Scheduled only', '0', '0', 36, '1142.29'), ('Monthly extra', '50', '0', 32, '993.77'), ('Combined extra', '50', '500', 30, '926.87')]
    for label, extra, lump, payoff, interest in expected:
        regular, month, total_interest, total_paid = schedule(extra, lump)
        assert month == payoff and total_interest == Decimal(interest)
        print(f'{label}: payment={regular}, months={month}, interest={total_interest}, total={total_paid}')
    print('Independent decimal reference checks passed.')
