"""
Check all Mwamba loans to see the interest calculation pattern
"""

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

# Get Mwamba product
try:
    mwamba = LoanProduct.objects.get(product_type='mwamba')
    print("=" * 80)
    print(f"MWAMBA PRODUCT SETTINGS")
    print("=" * 80)
    print(f"Name: {mwamba.name}")
    print(f"Interest Rate: {mwamba.interest_rate}%")
    print(f"Processing Fee: {mwamba.processing_fee}%")
    print(f"Duration Months: {mwamba.duration_months}")
    print(f"Min Duration: {mwamba.min_duration} days")
    print(f"Max Duration: {mwamba.max_duration} days")
except LoanProduct.DoesNotExist:
    print("No Mwamba product found!")
    exit(1)

# Get all Mwamba loans
mwamba_loans = Loan.objects.filter(
    application__loan_product__product_type='mwamba'
).order_by('-created_at')[:10]

print(f"\n" + "=" * 80)
print(f"RECENT MWAMBA LOANS (Last 10)")
print("=" * 80)

if not mwamba_loans:
    print("No Mwamba loans found!")
else:
    for loan in mwamba_loans:
        print(f"\n{'-' * 80}")
        print(f"Loan: {loan.loan_number}")
        print(f"Borrower: {loan.borrower.get_full_name()}")
        print(f"Status: {loan.status}")
        print(f"Created: {loan.created_at.strftime('%Y-%m-%d %H:%M')}")
        
        print(f"\nAmounts:")
        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:           KES {loan.total_amount:,.2f}")
        
        print(f"\nDuration:")
        print(f"  Days: {loan.duration_days}")
        print(f"  Months (calculated): {loan.duration_days / 30:.2f}")
        
        # 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
        
        print(f"\nInterest Analysis:")
        print(f"  Rate: {mwamba.interest_rate}%")
        print(f"  Calculation: {loan.principal_amount} × {interest_rate} × {months} = {expected_interest:,.2f}")
        print(f"  Expected: KES {expected_interest:,.2f}")
        print(f"  Actual:   KES {loan.interest_amount:,.2f}")
        print(f"  Match: {'✓' if abs(expected_interest - loan.interest_amount) < Decimal('0.01') else '✗'}")
        
        if abs(expected_interest - loan.interest_amount) >= Decimal('0.01'):
            difference = loan.interest_amount - expected_interest
            print(f"  Difference: KES {difference:,.2f}")
            
            # Try to figure out what months value was used
            if loan.principal_amount > 0 and interest_rate > 0:
                actual_months = loan.interest_amount / (loan.principal_amount * interest_rate)
                print(f"  Actual months used: {actual_months:.4f}")

print(f"\n" + "=" * 80)
print("ANALYSIS COMPLETE")
print("=" * 80)
