import os
import django

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

from loans.models import LoanProduct
from decimal import Decimal

# Get Mwamba product
try:
    mwamba = LoanProduct.objects.get(product_type='mwamba')
    
    print(f"\n{'='*60}")
    print(f"MWAMBA PRODUCT CALCULATION TEST")
    print(f"{'='*60}\n")
    
    print(f"Product: {mwamba.name}")
    print(f"Interest Rate: {mwamba.interest_rate}%")
    print(f"Processing Fee: {mwamba.processing_fee}%")
    print(f"Duration: {mwamba.min_duration}-{mwamba.max_duration} days")
    
    # Test calculation for 50,000 for 90 days
    principal = Decimal('50000')
    duration_days = 90
    months = duration_days / 30  # 3 months
    
    print(f"\nTest Loan:")
    print(f"  Principal: KES {principal:,.2f}")
    print(f"  Duration: {duration_days} days ({months} months)")
    
    # Calculate interest
    interest = mwamba.calculate_interest(principal, months)
    print(f"\nInterest Calculation:")
    print(f"  {principal} × {mwamba.interest_rate}% × {months} months = KES {interest:,.2f}")
    
    # Calculate processing fee
    processing_fee = mwamba.calculate_processing_fee(principal, months)
    print(f"\nProcessing Fee Calculation:")
    print(f"  {principal} × {mwamba.processing_fee}% = KES {processing_fee:,.2f}")
    
    # Check if it's charged monthly for Mwamba
    if mwamba.product_type == 'mwamba':
        print(f"  Note: Mwamba processing fee is ONE-TIME (not monthly)")
    
    # Calculate total
    total = principal + interest + processing_fee
    print(f"\nTotal Calculation:")
    print(f"  {principal:,.2f} + {interest:,.2f} + {processing_fee:,.2f} = {total:,.2f}")
    
    print(f"\n{'='*60}")
    print(f"EXPECTED TOTAL: KES {total:,.2f}")
    print(f"{'='*60}\n")
    
    # Now test what the system settings say
    print(f"\nSystem Settings Check:")
    print(f"  Interest Rate (from settings): {mwamba.get_interest_rate()}%")
    print(f"  Processing Fee (from settings): {mwamba.get_processing_fee()}%")
    
    # Recalculate with system settings
    interest_from_settings = principal * (Decimal(str(mwamba.get_interest_rate())) / Decimal('100')) * Decimal(str(months))
    processing_fee_from_settings = principal * (Decimal(str(mwamba.get_processing_fee())) / Decimal('100'))
    total_from_settings = principal + interest_from_settings + processing_fee_from_settings
    
    print(f"\nUsing System Settings:")
    print(f"  Interest: KES {interest_from_settings:,.2f}")
    print(f"  Processing Fee: KES {processing_fee_from_settings:,.2f}")
    print(f"  Total: KES {total_from_settings:,.2f}")
    
except LoanProduct.DoesNotExist:
    print("Mwamba product not found")
