"""
Verify that loan totals are correct in the database
"""
import os
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal

# Check the specific loans mentioned
loan_numbers = ['LOAN-000193', 'LOAN-000195']

print("=" * 80)
print("VERIFYING LOAN TOTALS IN DATABASE")
print("=" * 80)

for loan_number in loan_numbers:
    try:
        loan = Loan.objects.get(loan_number=loan_number)
        
        # Calculate what total should be
        calculated_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        
        # Get what's stored in DB
        stored_total = loan.total_amount
        
        # Check if they match
        matches = (calculated_total == stored_total)
        
        print(f"\n{loan_number}:")
        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"  ---")
        print(f"  Calculated Total: KES {calculated_total:,.2f}")
        print(f"  Stored Total:     KES {stored_total:,.2f}")
        print(f"  Match: {'✓ YES' if matches else '✗ NO - MISMATCH!'}")
        
        # Also check outstanding amount calculation
        amount_paid = loan.amount_paid
        outstanding = loan.outstanding_amount
        calculated_outstanding = stored_total - amount_paid
        
        print(f"\n  Amount Paid:      KES {amount_paid:,.2f}")
        print(f"  Outstanding (property): KES {outstanding:,.2f}")
        print(f"  Outstanding (calc):     KES {calculated_outstanding:,.2f}")
        
    except Loan.DoesNotExist:
        print(f"\n{loan_number}: NOT FOUND")

print("\n" + "=" * 80)
