#!/usr/bin/env python
"""
Fix loan database values to match the correct calculated amounts
The database has outdated interest_amount, processing_fee, and total_amount values.
This script updates them to match the current system rates.
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal

def fix_loan_amounts():
    """Update all loans with incorrect amounts"""
    
    # Get all loans
    loans = Loan.objects.all()
    
    fixed_count = 0
    errors = []
    
    print("=" * 80)
    print("FIXING LOAN DATABASE VALUES")
    print("=" * 80)
    
    for loan in loans:
        try:
            # Get current calculated values (using current system rates)
            correct_interest = loan.get_display_interest_amount()
            correct_processing_fee = loan.get_display_processing_fee_amount()
            correct_total = loan.principal_amount + correct_interest + correct_processing_fee
            
            # Check if values need updating
            needs_update = (
                loan.interest_amount != correct_interest or
                loan.processing_fee != correct_processing_fee or
                loan.total_amount != correct_total
            )
            
            if needs_update:
                print(f"\n{loan.loan_number} - {loan.borrower.get_full_name()}")
                print(f"  OLD: Interest={loan.interest_amount:,.2f}, Fee={loan.processing_fee:,.2f}, Total={loan.total_amount:,.2f}")
                print(f"  NEW: Interest={correct_interest:,.2f}, Fee={correct_processing_fee:,.2f}, Total={correct_total:,.2f}")
                
                # Update the loan
                loan.interest_amount = correct_interest
                loan.processing_fee = correct_processing_fee
                loan.total_amount = correct_total
                loan.save()
                
                fixed_count += 1
                print(f"  ✓ FIXED")
        
        except Exception as e:
            error_msg = f"{loan.loan_number}: {str(e)}"
            errors.append(error_msg)
            print(f"  ✗ ERROR: {str(e)}")
    
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Total loans checked: {loans.count()}")
    print(f"Loans fixed: {fixed_count}")
    print(f"Errors: {len(errors)}")
    
    if errors:
        print("\nErrors encountered:")
        for error in errors:
            print(f"  - {error}")
    
    return fixed_count, errors

if __name__ == '__main__':
    print("\nThis script will update loan database values to match calculated amounts.")
    print("The calculated amounts use the current system rates for each loan product.")
    
    response = input("\nDo you want to proceed? (yes/no): ")
    
    if response.lower() in ['yes', 'y']:
        fixed_count, errors = fix_loan_amounts()
        
        if fixed_count > 0 and len(errors) == 0:
            print("\n✓ All loans have been successfully updated!")
        elif fixed_count > 0:
            print(f"\n⚠ {fixed_count} loans updated, but {len(errors)} errors occurred.")
        else:
            print("\n✓ No loans needed updating.")
    else:
        print("\nOperation cancelled.")
