#!/usr/bin/env python
"""Check processing fee issue for LOAN-000086"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal

# Find the loan
loan = Loan.objects.filter(loan_number='LOAN-000086').first()

if loan:
    print(f"\n{'='*60}")
    print(f"LOAN DETAILS FOR {loan.loan_number}")
    print(f"{'='*60}")
    print(f"Borrower: {loan.borrower.first_name} {loan.borrower.last_name}")
    print(f"Principal Amount: KES {loan.principal_amount:,.2f}")
    print(f"\n{'='*60}")
    print(f"PROCESSING FEE ANALYSIS")
    print(f"{'='*60}")
    
    # Check stored processing fee
    print(f"Stored Processing Fee: KES {loan.processing_fee:,.2f}")
    
    # Check loan product
    if loan.application and loan.application.loan_product:
        product = loan.application.loan_product
        print(f"Loan Product: {product.name}")
        print(f"Product Type: {product.product_type}")
        print(f"Product Processing Fee Rate: {product.get_processing_fee()}%")
        
        # Calculate what it should be
        correct_fee = loan.principal_amount * Decimal(str(product.get_processing_fee())) / Decimal('100')
        print(f"Calculated Processing Fee (from product): KES {correct_fee:,.2f}")
    else:
        print(f"No loan product found!")
    
    # What the view is calculating (hardcoded 2%)
    wrong_fee = loan.principal_amount * Decimal('0.02')
    print(f"\nWhat the view is calculating (2%): KES {wrong_fee:,.2f}")
    
    print(f"\n{'='*60}")
    print(f"ISSUE IDENTIFIED:")
    print(f"{'='*60}")
    print(f"The processing fees report view is hardcoding 2% for all loans")
    print(f"instead of using the actual processing fee from the loan record")
    print(f"or the loan product's processing fee rate.")
    print(f"\nCorrect Fee: KES {loan.processing_fee:,.2f}")
    print(f"Displayed Fee: KES {wrong_fee:,.2f}")
    print(f"Difference: KES {abs(loan.processing_fee - wrong_fee):,.2f}")
else:
    print("Loan LOAN-000086 not found!")
