"""
Check the Mwamba product settings to understand why interest is 2000 instead of 6000
"""

import os
import django
from decimal import Decimal

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

from loans.models import LoanProduct, Loan
from utils.models import SystemSetting

def check_mwamba_settings():
    """Check Mwamba product and system settings"""
    
    print("=" * 80)
    print("CHECKING MWAMBA PRODUCT SETTINGS")
    print("=" * 80)
    
    try:
        mwamba = LoanProduct.objects.get(product_type='mwamba')
    except LoanProduct.DoesNotExist:
        print("\n✗ Mwamba product not found!")
        return
    
    print(f"\nMwamba Product (Database):")
    print(f"  Name: {mwamba.name}")
    print(f"  Interest Rate (model): {mwamba.interest_rate}%")
    print(f"  Processing Fee (model): {mwamba.processing_fee}%")
    print(f"  Min Duration: {mwamba.min_duration} days")
    print(f"  Max Duration: {mwamba.max_duration} days")
    
    # Check system settings
    print(f"\nSystem Settings (Override):")
    interest_setting = SystemSetting.objects.filter(key='mwamba_interest_rate').first()
    if interest_setting:
        print(f"  mwamba_interest_rate: {interest_setting.value}")
    else:
        print(f"  mwamba_interest_rate: Not set (using model default)")
    
    processing_fee_setting = SystemSetting.objects.filter(key='mwamba_processing_fee').first()
    if processing_fee_setting:
        print(f"  mwamba_processing_fee: {processing_fee_setting.value}")
    else:
        print(f"  mwamba_processing_fee: Not set (using model default)")
    
    # Check what get_interest_rate() and get_processing_fee() return
    print(f"\nEffective Rates (via get methods):")
    print(f"  Interest Rate: {mwamba.get_interest_rate()}%")
    print(f"  Processing Fee: {mwamba.get_processing_fee()}%")
    
    # Now check LOAN-000131
    print(f"\n" + "=" * 80)
    print("CHECKING LOAN-000131")
    print("=" * 80)
    
    try:
        loan = Loan.objects.get(loan_number='LOAN-000131')
    except Loan.DoesNotExist:
        print("\n✗ Loan LOAN-000131 not found!")
        return
    
    print(f"\nLoan Details:")
    print(f"  Borrower: {loan.borrower.get_full_name()}")
    print(f"  Principal: KES {loan.principal_amount:,.2f}")
    print(f"  Duration: {loan.duration_days} days")
    print(f"  Interest (stored): KES {loan.interest_amount:,.2f}")
    print(f"  Processing Fee (stored): KES {loan.processing_fee:,.2f}")
    print(f"  Total (stored): KES {loan.total_amount:,.2f}")
    
    # Calculate what it should be
    months = Decimal(str(loan.duration_days)) / Decimal('30')
    print(f"\nCalculation Analysis:")
    print(f"  Duration in months: {months}")
    
    # Using current product settings
    current_interest_rate = Decimal(str(mwamba.get_interest_rate())) / Decimal('100')
    current_processing_fee_rate = Decimal(str(mwamba.get_processing_fee())) / Decimal('100')
    
    expected_interest = loan.principal_amount * current_interest_rate * months
    expected_processing_fee = loan.principal_amount * current_processing_fee_rate
    expected_total = loan.principal_amount + expected_interest + expected_processing_fee
    
    print(f"\nExpected (with current rates):")
    print(f"  Interest: {loan.principal_amount:,.2f} × {current_interest_rate} × {months} = KES {expected_interest:,.2f}")
    print(f"  Processing Fee: {loan.principal_amount:,.2f} × {current_processing_fee_rate} = KES {expected_processing_fee:,.2f}")
    print(f"  Total: KES {expected_total:,.2f}")
    
    # Reverse engineer what rates were used
    actual_interest_rate = loan.interest_amount / (loan.principal_amount * months)
    actual_processing_fee_rate = loan.processing_fee / loan.principal_amount
    
    print(f"\nReverse Engineered (what was actually used):")
    print(f"  Interest Rate: {actual_interest_rate * 100:.2f}% per month")
    print(f"  Processing Fee Rate: {actual_processing_fee_rate * 100:.2f}%")
    
    # Check if rates match
    print(f"\n" + "=" * 80)
    print("DIAGNOSIS")
    print("=" * 80)
    
    if abs(actual_interest_rate * 100 - Decimal(str(mwamba.get_interest_rate()))) > Decimal('0.01'):
        print(f"\n⚠️  INTEREST RATE MISMATCH!")
        print(f"  Expected: {mwamba.get_interest_rate()}% per month")
        print(f"  Used: {actual_interest_rate * 100:.2f}% per month")
        print(f"  Difference: {(Decimal(str(mwamba.get_interest_rate())) - actual_interest_rate * 100):.2f}%")
    else:
        print(f"\n✓ Interest rate is correct")
    
    if abs(actual_processing_fee_rate * 100 - Decimal(str(mwamba.get_processing_fee()))) > Decimal('0.01'):
        print(f"\n⚠️  PROCESSING FEE RATE MISMATCH!")
        print(f"  Expected: {mwamba.get_processing_fee()}%")
        print(f"  Used: {actual_processing_fee_rate * 100:.2f}%")
        print(f"  Difference: {(Decimal(str(mwamba.get_processing_fee())) - actual_processing_fee_rate * 100):.2f}%")
    else:
        print(f"\n✓ Processing fee rate is correct")
    
    # Check all system settings
    print(f"\n" + "=" * 80)
    print("ALL MWAMBA SYSTEM SETTINGS")
    print("=" * 80)
    
    mwamba_settings = SystemSetting.objects.filter(key__startswith='mwamba')
    if mwamba_settings.exists():
        for setting in mwamba_settings:
            print(f"  {setting.key}: {setting.value}")
    else:
        print("  No Mwamba-specific system settings found")

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