"""
Fix loan totals in the database through Django ORM.

Finds all loans where total_amount != principal_amount + interest_amount + processing_fee
and corrects them.
"""
import os
import sys
import django

# Set production database credentials before Django loads settings.
# These match the values in .env — setting them explicitly ensures the script
# works even if dotenv fails to load (e.g. wrong working directory on the server).
os.environ.setdefault('DB_NAME', 'xygbfpsg_graz')
os.environ.setdefault('DB_USER', 'xygbfpsg_graz')
os.environ.setdefault('DB_PASSWORD', ',qdN3O_!}oC67(]W')
os.environ.setdefault('DB_HOST', 'localhost')
os.environ.setdefault('DB_PORT', '3306')

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)
