"""
test_rollover.py
----------------
Tests the rollover calculation against this business's actual rules:

  Business model: interest is PRE-DEDUCTED before disbursement.
  - total_amount = principal_amount  (what the customer repays)
  - interest_amount stored for accounting only, not in customer balance
  - outstanding_amount = principal_amount + penalties - amount_paid_since_rollover

  On rollover:
  - New total_amount = new_principal + rollover_fee
  - Rollover fee IS a real customer charge (added to what they owe)
  - Old payments are excluded via rollover_payment_offset
  - Outstanding after rollover = new_principal + rollover_fee (no new payments yet)

All DB changes are rolled back — the database is left untouched.

Run: python test_rollover.py
"""
import os, sys, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from decimal import Decimal
from django.utils import timezone
from django.contrib.auth import get_user_model
from loans.models import LoanProduct, LoanApplication, Loan, RolloverRequest, Repayment
from django.db import transaction

User = get_user_model()
admin = User.objects.get(username='admin')
SEP = '=' * 62

def chk(checks, label, actual, expected):
    ok = (actual == expected)
    if isinstance(actual, Decimal):
        line = f"  {label:<26} KES {actual:>12,.2f}"
        exp  = f"KES {expected:>12,.2f}"
    else:
        line = f"  {label:<26} {str(actual):<16}"
        exp  = str(expected)
    mark = '✓' if ok else f'✗  (expected {exp})'
    print(f"{line}  {mark}")
    checks.append(ok)

print(SEP)
print('  ROLLOVER CALCULATION TEST')
print(SEP)

product = LoanProduct.objects.first()
print(f'\nProduct:       {product.name}  ({product.product_type})')
print(f'Interest rate: {product.interest_rate}%')
print(f'Rollover fee:  {product.rollover_fee_percentage}%')
print(f'Pre-deducted interest model: total_amount = principal_amount only')

# ── Original loan ─────────────────────────────────────────────────────────────
principal     = Decimal('100000')
duration_days = 90
months        = Decimal('3')
interest      = product.calculate_interest(principal, months)
proc_fee      = product.calculate_processing_fee(principal, months)
# In pre-deduction model: customer owes only principal
orig_total    = principal   # signal enforces this

print(f'\nORIGINAL LOAN')
print(f'  Principal:              KES {principal:>12,.2f}')
print(f'  Interest (accounting):  KES {interest:>12,.2f}  (pre-deducted, not in balance)')
print(f'  Customer total:         KES {orig_total:>12,.2f}')

# ── Rollover params ───────────────────────────────────────────────────────────
new_principal = Decimal('80000')
new_duration  = 60
new_months    = Decimal('2')
rollover_fee  = (new_principal * product.rollover_fee_percentage / 100).quantize(Decimal('0.01'))
new_interest  = product.calculate_interest(new_principal, new_months)
# After rollover: customer owes new_principal + rollover_fee
new_total     = new_principal + rollover_fee

partial_payment = Decimal('20000')
# Outstanding before rollover = principal - amount_paid = 100000 - 20000 = 80000
expected_outstanding_before = principal - partial_payment
# Outstanding after rollover = new_total (no new payments yet)
expected_outstanding_after  = new_total

print(f'\nROLLOVER PARAMETERS')
print(f'  New principal:          KES {new_principal:>12,.2f}')
print(f'  Rollover fee ({product.rollover_fee_percentage}%):     KES {rollover_fee:>12,.2f}')
print(f'  New interest (acctg):   KES {new_interest:>12,.2f}')
print(f'  New customer total:     KES {new_total:>12,.2f}  (principal + rollover_fee)')
print(f'\nEXPECTED AFTER ROLLOVER')
print(f'  Outstanding before:     KES {expected_outstanding_before:>12,.2f}')
print(f'  Outstanding after:      KES {expected_outstanding_after:>12,.2f}')

checks = []

try:
    with transaction.atomic():
        User.objects.filter(username='test.rollover').delete()
        borrower = User.objects.create(
            username='test.rollover', first_name='Test', last_name='Rollover',
            phone_number='+254799999999', role='borrower', status='active',
            is_active=True, password='!unusable',
        )
        app = LoanApplication.objects.create(
            borrower=borrower, loan_product=product, requested_amount=principal,
            requested_duration=duration_days, interest_amount=interest,
            processing_fee_amount=proc_fee, total_amount=orig_total,
            status='approved', repayment_method='weekly',
            reviewed_by=admin, reviewed_at=timezone.now(),
        )
        now = timezone.now()
        loan = Loan.objects.create(
            application=app, borrower=borrower,
            principal_amount=principal, interest_amount=interest,
            processing_fee=proc_fee, total_amount=orig_total,
            disbursement_date=now, due_date=now + timezone.timedelta(days=duration_days),
            duration_days=duration_days, status='active',
            rollover_payment_offset=Decimal('0'),
        )
        print(f'\nCreated: {borrower.get_full_name()}  {app.application_number}  {loan.loan_number}')
        print(f'  Loan total_amount after create: KES {loan.total_amount:,.2f}  '
              f'(signal should enforce = principal = {orig_total:,.2f})')

        # Partial payment via Repayment
        Repayment.objects.create(loan=loan, amount=partial_payment,
                                 payment_method='cash', payment_date=timezone.now())
        Loan.objects.filter(pk=loan.pk).update(_amount_paid_cache=partial_payment)
        loan.refresh_from_db()

        outstanding_before = loan.outstanding_amount
        print(f'\nPartial payment: KES {partial_payment:,.2f}')
        print(f'Outstanding:     KES {outstanding_before:,.2f}  (expected {expected_outstanding_before:,.2f})')

        # Create and approve rollover
        rr = RolloverRequest.objects.create(
            loan=loan, borrower=borrower,
            requested_amount=new_principal, requested_duration=new_duration,
            rollover_fee=rollover_fee, reason='Automated test', status='pending',
        )
        updated_loan = rr.approve(approved_by=admin, notes='Automated test')
        updated_loan.refresh_from_db()

        print(f'\nROLLED-OVER LOAN — verification')
        print('-' * 62)

        chk(checks, 'Principal:',          updated_loan.principal_amount,       new_principal)
        chk(checks, 'Interest (acctg):',   updated_loan.interest_amount,        new_interest)
        chk(checks, 'Total (customer):',   updated_loan.total_amount,           new_total)
        chk(checks, 'Duration (days):',    Decimal(updated_loan.duration_days), Decimal(new_duration))
        chk(checks, 'Status:',             updated_loan.status,                 'active')
        chk(checks, 'is_rolled_over:',     updated_loan.is_rolled_over,         True)
        chk(checks, 'payment_offset:',     updated_loan.rollover_payment_offset, partial_payment)

        outstanding_after = updated_loan.outstanding_amount
        chk(checks, 'Outstanding after:',  outstanding_after,                   expected_outstanding_after)

        due_ok = updated_loan.due_date > updated_loan.disbursement_date
        checks.append(due_ok)
        print(f'  {"Due date valid:":<26} {str(updated_loan.due_date)[:19]}  {"✓" if due_ok else "✗"}')

        raise Exception('__ROLLBACK__')

except Exception as e:
    if '__ROLLBACK__' not in str(e):
        import traceback
        traceback.print_exc()
        sys.exit(1)

print('\n' + '-' * 62)
passed = sum(1 for c in checks if c)
total  = len(checks)
print(f'Result: {passed}/{total} checks passed')
if passed == total:
    print('ALL PASS ✓')
else:
    print('SOME FAILED ✗')
print('\nTest data rolled back — database unchanged.')
print(SEP)
