"""
Test Loan Total Amount Calculation Fix

This script tests that the loan total amount bug has been fixed.
"""

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal

def test_loan_calculations():
    """Test that all loans have correct total_amount calculations"""
    
    print("=" * 80)
    print("TESTING LOAN TOTAL AMOUNT CALCULATIONS")
    print("=" * 80)
    print()
    
    # Get all active loans
    all_loans = Loan.active_objects.all()
    print(f"📊 Testing {all_loans.count()} loans...")
    print()
    
    correct_count = 0
    incorrect_count = 0
    
    for loan in all_loans:
        # Calculate expected total
        expected_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        
        # Check if actual matches expected
        if loan.total_amount == expected_total:
            correct_count += 1
        else:
            incorrect_count += 1
            difference = expected_total - loan.total_amount
            
            print(f"❌ INCORRECT: Loan {loan.loan_number}")
            print(f"   Borrower: {loan.borrower.get_full_name()}")
            print(f"   Principal: KES {loan.principal_amount:,.2f}")
            print(f"   Interest: KES {loan.interest_amount:,.2f}")
            print(f"   Processing Fee: KES {loan.processing_fee:,.2f}")
            print(f"   Expected Total: KES {expected_total:,.2f}")
            print(f"   Actual Total: KES {loan.total_amount:,.2f}")
            print(f"   Difference: KES {difference:,.2f}")
            print()
    
    print("=" * 80)
    print("TEST RESULTS")
    print("=" * 80)
    print(f"✅ Correct: {correct_count}")
    print(f"❌ Incorrect: {incorrect_count}")
    print()
    
    if incorrect_count == 0:
        print("🎉 SUCCESS! All loans have correct total amounts!")
        print("   Formula: Total = Principal + Interest + Processing Fee")
    else:
        print("⚠️  WARNING! Some loans have incorrect totals.")
        print("   Run: python fix_loan_total_amount_bug.py")
    
    print("=" * 80)
    
    return incorrect_count == 0

if __name__ == '__main__':
    success = test_loan_calculations()
    exit(0 if success else 1)
