"""
Test script to verify loan edit recalculation fix
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from decimal import Decimal
from loans.models import Loan

# Find the loan LOAN-000191
try:
    loan = Loan.objects.get(loan_number='LOAN-000191')
    print(f"Found loan: {loan.loan_number}")
    
    print(f"\nBefore edit:")
    print(f"  Principal: KES {loan.principal_amount}")
    print(f"  Interest: KES {loan.interest_amount}")
    print(f"  Processing Fee: KES {loan.processing_fee}")
    print(f"  Total Amount: KES {loan.total_amount}")
    
    # Edit the loan amounts
    loan.principal_amount = Decimal('12800.48')
    loan.interest_amount = Decimal('2000.00')  # Changed from 2560.10
    loan.processing_fee = Decimal('200.00')     # Changed from 256.01
    
    # Save the loan - the pre_save signal should recalculate total_amount
    loan.save()
    
    # Refresh from database
    loan.refresh_from_db()
    
    print(f"\nAfter edit:")
    print(f"  Principal: KES {loan.principal_amount}")
    print(f"  Interest: KES {loan.interest_amount}")
    print(f"  Processing Fee: KES {loan.processing_fee}")
    print(f"  Total Amount: KES {loan.total_amount}")
    
    expected_total = Decimal('12800.48') + Decimal('2000.00') + Decimal('200.00')
    print(f"\nExpected Total: KES {expected_total}")
    print(f"Actual Total: KES {loan.total_amount}")
    
    if loan.total_amount == expected_total:
        print("\n✅ SUCCESS: Total amount recalculated correctly!")
    else:
        print(f"\n❌ FAILED: Total amount is {loan.total_amount}, expected {expected_total}")
        print(f"   Difference: KES {loan.total_amount - expected_total}")

except Loan.DoesNotExist:
    print("Loan LOAN-000191 not found. Please check the loan number.")
except Exception as e:
    print(f"Error: {e}")
    import traceback
    traceback.print_exc()
