"""
Fix the interest calculation for existing Mwamba loans that have incorrect interest amounts.

The bug: Some loans were created using product.duration_months (2) instead of actual loan duration.
This resulted in loans with 60-day or 180-day durations being charged interest for only 1.2 months.
"""

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 fix_mwamba_interest():
    """Fix interest calculation for Mwamba loans"""
    
    print("=" * 80)
    print("FIXING MWAMBA LOAN INTEREST CALCULATIONS")
    print("=" * 80)
    
    # Get Mwamba product
    mwamba = LoanProduct.objects.get(product_type='mwamba')
    print(f"\nMwamba Product:")
    print(f"  Interest Rate: {mwamba.interest_rate}%")
    print(f"  Processing Fee: {mwamba.processing_fee}%")
    
    # Get all Mwamba loans with incorrect interest
    mwamba_loans = Loan.objects.filter(
        application__loan_product__product_type='mwamba',
        status='active'
    ).order_by('created_at')
    
    print(f"\nFound {mwamba_loans.count()} active Mwamba loans")
    
    fixed_count = 0
    skipped_count = 0
    
    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
        
        # Check if interest is wrong
        if abs(expected_interest - loan.interest_amount) >= Decimal('0.01'):
            print(f"\n{'-' * 80}")
            print(f"Loan: {loan.loan_number}")
            print(f"  Principal: KES {loan.principal_amount:,.2f}")
            print(f"  Duration: {loan.duration_days} days ({months} months)")
            print(f"  Current Interest: KES {loan.interest_amount:,.2f}")
            print(f"  Expected Interest: KES {expected_interest:,.2f}")
            print(f"  Difference: KES {expected_interest - loan.interest_amount:,.2f}")
            
            # Calculate new processing fee (should be correct already, but recalculate)
            processing_fee_rate = mwamba.processing_fee / Decimal('100')
            expected_processing_fee = loan.principal_amount * processing_fee_rate
            
            # Calculate new total
            new_total = loan.principal_amount + expected_interest + expected_processing_fee
            
            print(f"\n  Fixing:")
            print(f"    Old Total: KES {loan.total_amount:,.2f}")
            print(f"    New Interest: KES {expected_interest:,.2f}")
            print(f"    New Processing Fee: KES {expected_processing_fee:,.2f}")
            print(f"    New Total: KES {new_total:,.2f}")
            
            # Ask for confirmation
            response = input(f"\n  Fix this loan? (y/n): ")
            if response.lower() == 'y':
                with transaction.atomic():
                    # 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()
                    
                    print(f"  ✓ Fixed!")
                    fixed_count += 1
            else:
                print(f"  Skipped")
                skipped_count += 1
        else:
            print(f"✓ {loan.loan_number} - Interest is correct")
    
    print(f"\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Fixed: {fixed_count} loans")
    print(f"Skipped: {skipped_count} loans")
    print(f"Total processed: {fixed_count + skipped_count} loans")

if __name__ == '__main__':
    try:
        fix_mwamba_interest()
    except Exception as e:
        print(f"\n✗ Error: {str(e)}")
        import traceback
        traceback.print_exc()
