"""
Automatically fix ALL Mwamba loans with incorrect interest calculations.
"""

import os
import django
from decimal import Decimal

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan, LoanProduct
from django.db import transaction

def auto_fix_all_mwamba_loans():
    """Automatically fix all Mwamba loans with incorrect interest"""
    
    print("=" * 80)
    print("AUTO-FIXING ALL MWAMBA LOAN INTEREST CALCULATIONS")
    print("=" * 80)
    
    # Get Mwamba product
    try:
        mwamba = LoanProduct.objects.get(product_type='mwamba')
    except LoanProduct.DoesNotExist:
        print("No Mwamba product found!")
        return
    
    print(f"\nMwamba Product Settings:")
    print(f"  Interest Rate: {mwamba.interest_rate}%")
    print(f"  Processing Fee: {mwamba.processing_fee}%")
    
    # Get all Mwamba loans (including all statuses)
    mwamba_loans = Loan.objects.filter(
        application__loan_product__product_type='mwamba'
    ).order_by('created_at')
    
    print(f"\nFound {mwamba_loans.count()} total Mwamba loans")
    
    fixed_loans = []
    correct_loans = []
    
    with transaction.atomic():
        for loan in mwamba_loans:
            # Calculate what interest SHOULD be
            months = Decimal(str(loan.duration_days)) / Decimal('30')
            interest_rate = mwamba.interest_rate / Decimal('100')
            expected_interest = loan.principal_amount * interest_rate * months
            
            # Round to 2 decimal places for comparison
            expected_interest = expected_interest.quantize(Decimal('0.01'))
            current_interest = loan.interest_amount.quantize(Decimal('0.01'))
            
            # Check if interest is wrong (allow 0.01 difference for rounding)
            if abs(expected_interest - current_interest) >= Decimal('0.01'):
                # Calculate correct processing fee
                processing_fee_rate = mwamba.processing_fee / Decimal('100')
                expected_processing_fee = (loan.principal_amount * processing_fee_rate).quantize(Decimal('0.01'))
                
                # Calculate new total
                new_total = loan.principal_amount + expected_interest + expected_processing_fee
                
                # Store old values for logging
                old_interest = loan.interest_amount
                old_total = loan.total_amount
                
                # Update loan
                loan.interest_amount = expected_interest
                loan.processing_fee = expected_processing_fee
                loan.total_amount = new_total
                loan.save()
                
                # Update application too
                loan.application.interest_amount = expected_interest
                loan.application.processing_fee_amount = expected_processing_fee
                loan.application.total_amount = new_total
                loan.application.save()
                
                fixed_loans.append({
                    'loan_number': loan.loan_number,
                    'principal': loan.principal_amount,
                    'duration_days': loan.duration_days,
                    'months': months,
                    'old_interest': old_interest,
                    'new_interest': expected_interest,
                    'old_total': old_total,
                    'new_total': new_total,
                    'difference': expected_interest - old_interest
                })
            else:
                correct_loans.append(loan.loan_number)
    
    # Print results
    print(f"\n" + "=" * 80)
    print("FIXED LOANS")
    print("=" * 80)
    
    if fixed_loans:
        for fix in fixed_loans:
            print(f"\n{fix['loan_number']}:")
            print(f"  Principal: KES {fix['principal']:,.2f}")
            print(f"  Duration: {fix['duration_days']} days ({fix['months']} months)")
            print(f"  Interest: KES {fix['old_interest']:,.2f} → KES {fix['new_interest']:,.2f} (Δ {fix['difference']:+,.2f})")
            print(f"  Total: KES {fix['old_total']:,.2f} → KES {fix['new_total']:,.2f}")
    else:
        print("\nNo loans needed fixing!")
    
    print(f"\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"✓ Fixed: {len(fixed_loans)} loans")
    print(f"✓ Already correct: {len(correct_loans)} loans")
    print(f"✓ Total processed: {len(fixed_loans) + len(correct_loans)} loans")
    
    if fixed_loans:
        print(f"\n" + "=" * 80)
        print("VERIFICATION")
        print("=" * 80)
        print("\nAll Mwamba loans now have correct interest calculations:")
        print("Interest = Principal × 10% × (Duration in days / 30)")
        print("\nExamples:")
        print("  60 days (2 months): Principal × 10% × 2 = 20% total interest")
        print("  90 days (3 months): Principal × 10% × 3 = 30% total interest")
        print("  180 days (6 months): Principal × 10% × 6 = 60% total interest")

if __name__ == '__main__':
    try:
        auto_fix_all_mwamba_loans()
        print(f"\n✓ Script completed successfully!")
    except Exception as e:
        print(f"\n✗ Error: {str(e)}")
        import traceback
        traceback.print_exc()
