﻿"""
Production Fix for ALL Loans with Incorrect Calculations
This script will find and fix all loans with incorrect interest/processing fee calculations
"""
import os
import sys

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan, LoanApplication
from decimal import Decimal

print(f"\n{'='*80}")
print(f"COMPREHENSIVE LOAN CALCULATION FIX")
print(f"{'='*80}\n")

try:
    # Check all active loans
    print("Checking all active loans for calculation errors...\n")
    
    loans = Loan.objects.filter(status='active').select_related(
        'application', 'application__loan_product', 'borrower'
    )
    
    print(f"Found {loans.count()} active loan(s)\n")
    
    issues_found = 0
    fixed_loans = []
    
    for loan in loans:
        # Calculate what the values should be
        months = loan.duration_days / 30
        
        # Calculate correct interest
        correct_interest = loan.application.loan_product.calculate_interest(
            loan.principal_amount, months
        )
        
        # Calculate correct processing fee
        correct_processing_fee = loan.application.loan_product.calculate_processing_fee(
            loan.principal_amount, months
        )
        
        # Calculate correct total
        correct_total = loan.principal_amount + correct_interest + correct_processing_fee
        
        # Check if there are any discrepancies
        interest_wrong = abs(loan.interest_amount - correct_interest) > Decimal('0.01')
        processing_fee_wrong = abs(loan.processing_fee - correct_processing_fee) > Decimal('0.01')
        total_wrong = abs(loan.total_amount - correct_total) > Decimal('0.01')
        
        if interest_wrong or processing_fee_wrong or total_wrong:
            issues_found += 1
            
            print(f"{'='*80}")
            print(f"ISSUE FOUND: {loan.loan_number}")
            print(f"{'='*80}")
            print(f"Borrower: {loan.borrower.get_full_name()}")
            print(f"Product: {loan.application.loan_product.name}")
            print(f"Duration: {loan.duration_days} days ({months:.2f} months)")
            
            print(f"\nCurrent Values:")
            print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
            print(f"  Interest:        KES {loan.interest_amount:>12,.2f}")
            print(f"  Processing Fee:  KES {loan.processing_fee:>12,.2f}")
            print(f"  Total:           KES {loan.total_amount:>12,.2f}")
            
            print(f"\nCorrect Values:")
            print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
            print(f"  Interest:        KES {correct_interest:>12,.2f}")
            print(f"  Processing Fee:  KES {correct_processing_fee:>12,.2f}")
            print(f"  Total:           KES {correct_total:>12,.2f}")
            
            print(f"\nDifferences:")
            if interest_wrong:
                print(f"  Interest:        {correct_interest - loan.interest_amount:>+12,.2f}")
            if processing_fee_wrong:
                print(f"  Processing Fee:  {correct_processing_fee - loan.processing_fee:>+12,.2f}")
            if total_wrong:
                print(f"  Total:           {correct_total - loan.total_amount:>+12,.2f}")
            
            # Fix the loan
            print(f"\nApplying fix...")
            
            loan.interest_amount = correct_interest
            loan.processing_fee = correct_processing_fee
            loan.total_amount = correct_total
            loan.save()
            
            # Also fix the application
            app = loan.application
            app.interest_amount = correct_interest
            app.processing_fee_amount = correct_processing_fee
            app.total_amount = correct_total
            app.save()
            
            print(f"✅ Fixed {loan.loan_number} and {app.application_number}")
            
            fixed_loans.append({
                'loan_number': loan.loan_number,
                'borrower': loan.borrower.get_full_name(),
                'old_total': loan.total_amount,
                'new_total': correct_total,
                'difference': correct_total - loan.total_amount
            })
            
            print()
    
    print(f"\n{'='*80}")
    print(f"SUMMARY")
    print(f"{'='*80}\n")
    
    if issues_found == 0:
        print("✅ No issues found! All loans have correct calculations.")
    else:
        print(f"Found and fixed {issues_found} loan(s) with calculation errors:\n")
        
        for fixed in fixed_loans:
            print(f"  {fixed['loan_number']} - {fixed['borrower']}")
            print(f"    Old Total: KES {fixed['old_total']:,.2f}")
            print(f"    New Total: KES {fixed['new_total']:,.2f}")
            print(f"    Difference: +KES {fixed['difference']:,.2f}")
            print()
    
    print(f"{'='*80}")
    print(f"FIX COMPLETE!")
    print(f"{'='*80}\n")
    
except Exception as e:
    print(f"\n❌ ERROR: {str(e)}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
