"""
Run this with: python manage.py shell < fix_loans_shell.py
Or: python manage.py shell
Then paste this code
"""

from loans.models import Loan
from decimal import Decimal

print("=" * 80)
print("CHECKING AND FIXING LOAN TOTALS")
print("=" * 80)
print()

# Get all loans
all_loans = Loan.objects.all()
print(f"Total loans found: {all_loans.count()}")
print()

if all_loans.count() == 0:
    print("No loans found in database!")
    print("This might mean:")
    print("1. The database is empty")
    print("2. There's a database connection issue")
    print("3. The loans are in a different database")
else:
    fixed_count = 0
    
    for loan in all_loans:
        # Calculate correct total
        correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        
        if loan.total_amount != correct_total:
            print(f"Loan {loan.loan_number}:")
            print(f"  Principal: {loan.principal_amount}")
            print(f"  Interest: {loan.interest_amount}")
            print(f"  Processing Fee: {loan.processing_fee}")
            print(f"  Current Total: {loan.total_amount} (WRONG)")
            print(f"  Correct Total: {correct_total}")
            print(f"  Fixing...")
            
            loan.total_amount = correct_total
            loan.save()
            fixed_count += 1
            print(f"  ✓ Fixed!")
            print()
    
    print("=" * 80)
    print(f"Fixed {fixed_count} loans")
    print("=" * 80)
