import os, sys, django
os.environ['DJANGO_SETTINGS_MODULE'] = 'branch_system.settings'
django.setup()

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

User = get_user_model()
admin = User.objects.get(username='admin')
product = LoanProduct.objects.first()

principal = Decimal('100000')
months = Decimal('3')
interest = product.calculate_interest(principal, months)
proc_fee = product.calculate_processing_fee(principal, months)
orig_total = principal + interest + proc_fee
partial = Decimal('20000')
new_principal = Decimal('80000')
new_duration = 60
rollover_fee_amt = (new_principal * product.rollover_fee_percentage / 100).quantize(Decimal('0.01'))

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=90, 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=90),
            duration_days=90, status='active', rollover_payment_offset=Decimal('0'),
        )
        Repayment.objects.create(loan=loan, amount=partial, payment_method='cash', payment_date=timezone.now())
        Loan.objects.filter(pk=loan.pk).update(_amount_paid_cache=partial)
        loan.refresh_from_db()

        rr = RolloverRequest.objects.create(
            loan=loan, borrower=borrower, requested_amount=new_principal,
            requested_duration=new_duration, rollover_fee=rollover_fee_amt,
            reason='debug', status='pending',
        )

        print(f'rollover_fee on rr:          {rr.rollover_fee}')
        print(f'loan.amount_paid:            {loan.amount_paid}')
        print(f'loan.rollover_payment_offset:{loan.rollover_payment_offset}')

        # Manually trace approve()
        rf = rr.rollover_fee or Decimal('0.00')
        pa = new_principal
        d  = new_duration
        lp = loan.application.loan_product
        m  = max(1, d / 30)
        ia = lp.calculate_interest(pa, m)
        pf = lp.calculate_processing_fee(pa, m)
        ta = pa + ia + pf + rf
        print(f'\nManual trace:')
        print(f'  principal={pa}  interest={ia}  proc_fee={pf}  rollover_fee={rf}')
        print(f'  total = {pa} + {ia} + {pf} + {rf} = {ta}')

        updated = rr.approve(approved_by=admin)
        updated.refresh_from_db()
        print(f'\nAfter approve():')
        print(f'  total_amount:     {updated.total_amount}')
        print(f'  principal_amount: {updated.principal_amount}')
        print(f'  interest_amount:  {updated.interest_amount}')
        print(f'  processing_fee:   {updated.processing_fee}')
        print(f'  rollover_offset:  {updated.rollover_payment_offset}')
        print(f'  outstanding:      {updated.outstanding_amount}')

        raise Exception('rollback')

except Exception as e:
    if 'rollback' not in str(e):
        import traceback
        traceback.print_exc()
