"""
Fix loan totals in the LOCAL database through Django ORM
"""
import os
import django

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

from loans.models import Loan
from django.db.models import F
from decimal import Decimal

print("=" * 80)
print("FIXING LOAN TOTALS IN LOCAL DATABASE")
print("=" * 80)

# Find loans with incorrect totals
incorrect_loans = Loan.objects.exclude(
    total_amount=F('principal_amount') + F('interest_amount') + F('processing_fee')
)

count = incorrect_loans.count()
print(f"\nFound {count} loans with incorrect totals")

if count > 0:
    print("\nLoans to fix:")
    for loan in incorrect_loans:
        calculated = loan.principal_amount + loan.interest_amount + loan.processing_fee
        print(f"  {loan.loan_number}: {loan.total_amount} → {calculated} (diff: {calculated - loan.total_amount})")
    
    # Fix them
    print(f"\nFixing {count} loans...")
    fixed = 0
    for loan in incorrect_loans:
        loan.total_amount = loan.principal_amount + loan.interest_amount + loan.processing_fee
        loan.save()
        fixed += 1
    
    print(f"✓ Fixed {fixed} loans")
else:
    print("\n✓ All loans have correct totals!")

# Verify
print("\n" + "=" * 80)
print("VERIFICATION")
print("=" * 80)

total_loans = Loan.objects.count()
correct_loans = Loan.objects.filter(
    total_amount=F('principal_amount') + F('interest_amount') + F('processing_fee')
).count()
incorrect_loans = total_loans - correct_loans

print(f"\nTotal loans: {total_loans}")
print(f"Correct loans: {correct_loans}")
print(f"Incorrect loans: {incorrect_loans}")

if incorrect_loans == 0:
    print("\n✓ ALL LOANS ARE NOW CORRECT!")
else:
    print(f"\n✗ Still have {incorrect_loans} incorrect loans")

print("\n" + "=" * 80)
