"""
Fix Loan Total Amount Calculation Bug

This script fixes loans where total_amount was incorrectly calculated
without including the processing_fee.

The bug was in loans/views.py edit_loan() function:
    WRONG: loan.total_amount = principal_amount + interest_amount
    CORRECT: loan.total_amount = principal_amount + interest_amount + processing_fee

This script will:
1. Find all loans where total_amount != (principal_amount + interest_amount + processing_fee)
2. Recalculate and fix the total_amount
3. Log all changes
"""

import os
import django

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

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

def fix_loan_totals():
    """Fix incorrect loan total amounts"""
    
    print("=" * 80)
    print("LOAN TOTAL AMOUNT BUG FIX")
    print("=" * 80)
    print()
    
    # Get all active loans (not deleted)
    all_loans = Loan.active_objects.all()
    print(f"📊 Total loans to check: {all_loans.count()}")
    print()
    
    fixed_count = 0
    errors = []
    
    for loan in all_loans:
        try:
            # Calculate what the total SHOULD be
            correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
            
            # Check if current total is incorrect
            if loan.total_amount != correct_total:
                old_total = loan.total_amount
                difference = correct_total - old_total
                
                print(f"🔧 Fixing Loan {loan.loan_number}")
                print(f"   Borrower: {loan.borrower.get_full_name()}")
                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"   ❌ OLD Total: KES {old_total:,.2f}")
                print(f"   ✅ NEW Total: KES {correct_total:,.2f}")
                print(f"   📈 Difference: KES {difference:,.2f}")
                print()
                
                # Update the loan
                loan.total_amount = correct_total
                loan.save()
                
                fixed_count += 1
                
        except Exception as e:
            error_msg = f"Error fixing loan {loan.loan_number}: {str(e)}"
            print(f"❌ {error_msg}")
            errors.append(error_msg)
            print()
    
    print("=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"✅ Loans fixed: {fixed_count}")
    print(f"✓ Loans already correct: {all_loans.count() - fixed_count - len(errors)}")
    
    if errors:
        print(f"❌ Errors: {len(errors)}")
        for error in errors:
            print(f"   - {error}")
    
    print()
    print("=" * 80)
    print("FIX COMPLETE!")
    print("=" * 80)

if __name__ == '__main__':
    fix_loan_totals()
