"""
Comprehensive fix for loan calculation issues.
This script will:
1. Check all loan products for correct rates
2. Check all loan applications for correct calculations
3. Check all loans for correct calculations
4. Fix any discrepancies found
"""
import os
import django

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

from loans.models import Loan, LoanApplication, LoanProduct
from decimal import Decimal

print(f"\n{'='*70}")
print(f"COMPREHENSIVE LOAN CALCULATION FIX")
print(f"{'='*70}\n")

# Step 1: Check all loan products
print("Step 1: Checking Loan Products...")
print("-" * 70)

products = LoanProduct.objects.all()
for product in products:
    print(f"\n{product.name} ({product.product_type})")
    print(f"  Interest Rate: {product.interest_rate}%")
    print(f"  Processing Fee: {product.processing_fee}%")
    print(f"  Duration: {product.min_duration}-{product.max_duration} days")

# Step 2: Check all pending/approved loan applications
print(f"\n\nStep 2: Checking Loan Applications...")
print("-" * 70)

applications = LoanApplication.objects.filter(status__in=['pending', 'approved', 'under_review'])
issues_found = 0

for app in applications:
    # Calculate what the total should be
    principal = app.requested_amount
    months = max(1, app.requested_duration / 30)
    
    # Calculate interest
    interest = app.loan_product.calculate_interest(principal, months)
    
    # Calculate processing fee
    processing_fee = app.loan_product.calculate_processing_fee(principal, months)
    
    # Calculate correct total
    correct_total = principal + interest + processing_fee
    
    # Check if there's a mismatch
    if app.total_amount and abs(app.total_amount - correct_total) > Decimal('0.01'):
        issues_found += 1
        print(f"\n❌ Application {app.application_number}")
        print(f"   Borrower: {app.borrower.get_full_name()}")
        print(f"   Product: {app.loan_product.name}")
        print(f"   Principal: KES {principal:,.2f}")
        print(f"   Duration: {app.requested_duration} days ({months:.1f} months)")
        print(f"   Interest (DB): KES {app.interest_amount:,.2f}")
        print(f"   Interest (Calc): KES {interest:,.2f}")
        print(f"   Processing Fee (DB): KES {app.processing_fee_amount:,.2f}")
        print(f"   Processing Fee (Calc): KES {processing_fee:,.2f}")
        print(f"   Total (DB): KES {app.total_amount:,.2f}")
        print(f"   Total (Correct): KES {correct_total:,.2f}")
        print(f"   Difference: KES {correct_total - app.total_amount:,.2f}")
        
        # Fix it
        app.interest_amount = interest
        app.processing_fee_amount = processing_fee
        app.total_amount = correct_total
        app.save()
        print(f"   ✅ FIXED!")

if issues_found == 0:
    print("\n✅ All loan applications have correct calculations")
else:
    print(f"\n✅ Fixed {issues_found} loan application(s)")

# Step 3: Check all active loans
print(f"\n\nStep 3: Checking Active Loans...")
print("-" * 70)

loans = Loan.objects.filter(status='active')
issues_found = 0

for loan in loans:
    # Calculate correct total
    correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
    
    # Check if there's a mismatch
    if abs(loan.total_amount - correct_total) > Decimal('0.01'):
        issues_found += 1
        print(f"\n❌ 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"   Total (DB): KES {loan.total_amount:,.2f}")
        print(f"   Total (Correct): KES {correct_total:,.2f}")
        print(f"   Difference: KES {correct_total - loan.total_amount:,.2f}")
        
        # Fix it
        loan.total_amount = correct_total
        loan.save()
        print(f"   ✅ FIXED!")

if issues_found == 0:
    print("\n✅ All active loans have correct calculations")
else:
    print(f"\n✅ Fixed {issues_found} active loan(s)")

print(f"\n{'='*70}")
print(f"FIX COMPLETE")
print(f"{'='*70}\n")
