"""
Test that Mwamba loan interest is calculated correctly with the fixed code.
"""

import os
import django
from decimal import Decimal

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

from django.contrib.auth import get_user_model
from loans.models import LoanProduct, LoanApplication, Loan
from django.utils import timezone

User = get_user_model()

def test_mwamba_interest_calculation():
    """Test various Mwamba loan durations to ensure correct interest calculation"""
    
    print("=" * 80)
    print("TESTING MWAMBA INTEREST CALCULATION")
    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 a borrower
    borrower = User.objects.filter(role='borrower', is_active=True).first()
    if not borrower:
        print("\nNo borrower found! Please create a borrower first.")
        return
    
    print(f"\nBorrower: {borrower.get_full_name()}")
    
    # Test cases: (duration_days, expected_months, description)
    test_cases = [
        (30, Decimal('1.0'), "1 month"),
        (60, Decimal('2.0'), "2 months"),
        (90, Decimal('3.0'), "3 months"),
        (120, Decimal('4.0'), "4 months"),
        (180, Decimal('6.0'), "6 months"),
        (45, Decimal('1.5'), "1.5 months"),
        (75, Decimal('2.5'), "2.5 months"),
    ]
    
    print(f"\n" + "=" * 80)
    print("TEST CASES")
    print("=" * 80)
    
    all_passed = True
    
    for duration_days, expected_months, description in test_cases:
        print(f"\n{'-' * 80}")
        print(f"Test: {description} ({duration_days} days)")
        print(f"{'-' * 80}")
        
        principal = Decimal('100000.00')
        
        # Calculate expected values
        interest_rate = mwamba.interest_rate / Decimal('100')
        expected_interest = principal * interest_rate * expected_months
        processing_fee_rate = mwamba.processing_fee / Decimal('100')
        expected_processing_fee = principal * processing_fee_rate
        expected_total = principal + expected_interest + expected_processing_fee
        
        print(f"\nExpected Calculation:")
        print(f"  Principal: KES {principal:,.2f}")
        print(f"  Months: {expected_months}")
        print(f"  Interest: {principal:,.2f} × {interest_rate} × {expected_months} = KES {expected_interest:,.2f}")
        print(f"  Processing Fee: {principal:,.2f} × {processing_fee_rate} = KES {expected_processing_fee:,.2f}")
        print(f"  Total: KES {expected_total:,.2f}")
        
        # Create application (this will auto-calculate amounts)
        application = LoanApplication.objects.create(
            borrower=borrower,
            loan_product=mwamba,
            requested_amount=principal,
            requested_duration=duration_days,
            purpose=f"Test loan for {description}",
            repayment_method='monthly',
            status='pending'
        )
        
        print(f"\nActual Calculation:")
        print(f"  Interest: KES {application.interest_amount:,.2f}")
        print(f"  Processing Fee: KES {application.processing_fee_amount:,.2f}")
        print(f"  Total: KES {application.total_amount:,.2f}")
        
        # Verify
        interest_match = abs(application.interest_amount - expected_interest) < Decimal('0.01')
        processing_fee_match = abs(application.processing_fee_amount - expected_processing_fee) < Decimal('0.01')
        total_match = abs(application.total_amount - expected_total) < Decimal('0.01')
        
        if interest_match and processing_fee_match and total_match:
            print(f"\n✓ PASSED")
        else:
            print(f"\n✗ FAILED")
            if not interest_match:
                print(f"  Interest mismatch: Expected {expected_interest:,.2f}, Got {application.interest_amount:,.2f}")
            if not processing_fee_match:
                print(f"  Processing fee mismatch: Expected {expected_processing_fee:,.2f}, Got {application.processing_fee_amount:,.2f}")
            if not total_match:
                print(f"  Total mismatch: Expected {expected_total:,.2f}, Got {application.total_amount:,.2f}")
            all_passed = False
        
        # Clean up - delete the test application
        application.delete()
    
    print(f"\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    
    if all_passed:
        print("\n✓ ALL TESTS PASSED!")
        print("\nMwamba interest calculation is working correctly:")
        print("  Interest = Principal × 10% × (Duration in days ÷ 30)")
        print("\nExamples:")
        print("  30 days: 10% × 1 month = 10% total interest")
        print("  60 days: 10% × 2 months = 20% total interest")
        print("  90 days: 10% × 3 months = 30% total interest")
        print("  45 days: 10% × 1.5 months = 15% total interest")
    else:
        print("\n✗ SOME TESTS FAILED!")
        print("Please check the calculation logic.")

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