"""
Create 5 new Mwamba loans with different durations to verify interest calculation.
"""

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 create_test_mwamba_loans():
    """Create 5 Mwamba loans with different durations"""
    
    print("=" * 80)
    print("CREATING 5 TEST MWAMBA LOANS")
    print("=" * 80)
    
    # Get Mwamba product
    mwamba = LoanProduct.objects.get(product_type='mwamba')
    print(f"\nMwamba Product:")
    print(f"  Interest Rate: {mwamba.interest_rate}% per month")
    print(f"  Processing Fee: {mwamba.processing_fee}%")
    
    # Get or create borrowers
    borrowers = []
    for i in range(5):
        borrower = User.objects.filter(
            username=f'mwamba_test_{i+1}'
        ).first()
        
        if not borrower:
            borrower = User.objects.create_user(
                username=f'mwamba_test_{i+1}',
                email=f'mwamba_test_{i+1}@example.com',
                password='password123',
                first_name=f'Mwamba',
                last_name=f'Test{i+1}',
                phone_number=f'+25471234567{i}',
                role='borrower',
                is_active=True,
                status='active',
                monthly_income=Decimal('100000.00')
            )
            print(f"  Created borrower: {borrower.get_full_name()}")
        else:
            print(f"  Using borrower: {borrower.get_full_name()}")
        
        borrowers.append(borrower)
    
    # Get admin for approval
    admin = User.objects.filter(role='admin').first()
    if not admin:
        admin = User.objects.filter(is_superuser=True).first()
    
    # Test cases: (principal, duration_days, description)
    test_cases = [
        (Decimal('50000.00'), 30, "1 month (30 days)"),
        (Decimal('75000.00'), 60, "2 months (60 days)"),
        (Decimal('100000.00'), 90, "3 months (90 days)"),
        (Decimal('150000.00'), 120, "4 months (120 days)"),
        (Decimal('200000.00'), 180, "6 months (180 days)"),
    ]
    
    print(f"\n" + "=" * 80)
    print("CREATING LOANS")
    print("=" * 80)
    
    created_loans = []
    
    for idx, (principal, duration_days, description) in enumerate(test_cases):
        borrower = borrowers[idx]
        
        print(f"\n{'-' * 80}")
        print(f"Loan {idx + 1}: {description}")
        print(f"{'-' * 80}")
        
        # Calculate expected values
        months = Decimal(str(duration_days)) / Decimal('30')
        interest_rate = mwamba.interest_rate / Decimal('100')
        expected_interest = principal * interest_rate * 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"  Duration: {duration_days} days ({months} months)")
        print(f"  Interest: {principal:,.2f} × {mwamba.interest_rate}% × {months} = KES {expected_interest:,.2f}")
        print(f"  Processing Fee: {principal:,.2f} × {mwamba.processing_fee}% = KES {expected_processing_fee:,.2f}")
        print(f"  Total: KES {expected_total:,.2f}")
        
        # Create application
        application = LoanApplication.objects.create(
            borrower=borrower,
            loan_product=mwamba,
            requested_amount=principal,
            requested_duration=duration_days,
            purpose=f"Test Mwamba loan - {description}",
            repayment_method='monthly',
            status='pending'
        )
        
        print(f"\nApplication Created: {application.application_number}")
        print(f"  Interest Amount: KES {application.interest_amount:,.2f}")
        print(f"  Processing Fee: KES {application.processing_fee_amount:,.2f}")
        print(f"  Total Amount: KES {application.total_amount:,.2f}")
        
        # Verify calculation
        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✓ Calculation CORRECT!")
        else:
            print(f"\n✗ Calculation MISMATCH!")
            if not interest_match:
                print(f"  Interest: Expected {expected_interest:,.2f}, Got {application.interest_amount:,.2f}")
            if not processing_fee_match:
                print(f"  Processing Fee: Expected {expected_processing_fee:,.2f}, Got {application.processing_fee_amount:,.2f}")
            if not total_match:
                print(f"  Total: Expected {expected_total:,.2f}, Got {application.total_amount:,.2f}")
        
        # Approve and create loan
        loan = application.approve(
            approved_by=admin,
            notes=f"Test loan - {description}",
            disbursement_date=timezone.now()
        )
        
        print(f"\nLoan Created: {loan.loan_number}")
        print(f"  Status: {loan.status}")
        
        # Verify loan amounts match application
        loan_match = (
            loan.principal_amount == application.requested_amount and
            loan.interest_amount == application.interest_amount and
            loan.processing_fee == application.processing_fee_amount and
            loan.total_amount == application.total_amount
        )
        
        if loan_match:
            print(f"✓ Loan amounts match application")
        else:
            print(f"✗ Loan amounts don't match application!")
        
        created_loans.append({
            'loan': loan,
            'principal': principal,
            'duration_days': duration_days,
            'months': months,
            'expected_interest': expected_interest,
            'actual_interest': loan.interest_amount,
            'description': description
        })
    
    # Summary
    print(f"\n" + "=" * 80)
    print("SUMMARY OF CREATED LOANS")
    print("=" * 80)
    
    print(f"\n{'Loan Number':<15} {'Duration':<12} {'Principal':<15} {'Interest':<15} {'Total':<15} {'Status'}")
    print("-" * 95)
    
    all_correct = True
    for loan_data in created_loans:
        loan = loan_data['loan']
        expected = loan_data['expected_interest']
        actual = loan_data['actual_interest']
        match = abs(expected - actual) < Decimal('0.01')
        status = "✓ CORRECT" if match else "✗ WRONG"
        
        if not match:
            all_correct = False
        
        print(f"{loan.loan_number:<15} {loan_data['duration_days']:>3} days    KES {loan.principal_amount:>10,.2f}  KES {loan.interest_amount:>10,.2f}  KES {loan.total_amount:>10,.2f}  {status}")
    
    print(f"\n" + "=" * 80)
    print("INTEREST BREAKDOWN VERIFICATION")
    print("=" * 80)
    
    for loan_data in created_loans:
        loan = loan_data['loan']
        months = loan_data['months']
        interest_per_month = loan.principal_amount * Decimal('0.10')
        
        print(f"\n{loan.loan_number} - {loan_data['description']}:")
        print(f"  Principal: KES {loan.principal_amount:,.2f}")
        print(f"  Interest Rate: 10% per month")
        print(f"  Duration: {loan_data['duration_days']} days = {months} months")
        print(f"  Calculation:")
        
        # Show month-by-month breakdown
        for month in range(1, int(months) + 1):
            print(f"    Month {month}: 10% × KES {loan.principal_amount:,.2f} = KES {interest_per_month:,.2f}")
        
        # If there's a partial month
        if months % 1 != 0:
            partial = months % 1
            partial_interest = loan.principal_amount * Decimal('0.10') * Decimal(str(partial))
            print(f"    Partial ({partial:.2f} month): 10% × KES {loan.principal_amount:,.2f} × {partial:.2f} = KES {partial_interest:,.2f}")
        
        print(f"  Total Interest: KES {loan.interest_amount:,.2f}")
        print(f"  Total Amount: KES {loan.total_amount:,.2f}")
    
    print(f"\n" + "=" * 80)
    print("FINAL VERIFICATION")
    print("=" * 80)
    
    if all_correct:
        print("\n✓✓✓ SUCCESS! ALL 5 LOANS HAVE CORRECT INTEREST CALCULATIONS! ✓✓✓")
        print("\nThe interest calculation is working perfectly:")
        print("  • Each month charges exactly 10% of the principal")
        print("  • Partial months are calculated proportionally")
        print("  • No rounding errors or incorrect multipliers")
        print("\nFormula verified: Interest = Principal × 10% × (Days ÷ 30)")
    else:
        print("\n✗ SOME LOANS HAVE INCORRECT CALCULATIONS!")
        print("Please review the calculation logic.")
    
    return created_loans

if __name__ == '__main__':
    try:
        loans = create_test_mwamba_loans()
        print(f"\n✓ Script completed successfully!")
        print(f"✓ Created {len(loans)} test loans")
    except Exception as e:
        print(f"\n✗ Error: {str(e)}")
        import traceback
        traceback.print_exc()
