"""
Check the details of loan LOAN-000113 to see what's wrong with the interest calculation
"""

import os
import django
from decimal import Decimal

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

from loans.models import Loan

# Get the loan
loan = Loan.objects.get(loan_number='LOAN-000113')

print("=" * 80)
print(f"LOAN DETAILS: {loan.loan_number}")
print("=" * 80)

print(f"\nBasic Info:")
print(f"  Borrower: {loan.borrower.get_full_name()}")
print(f"  Product: {loan.application.loan_product.name}")
print(f"  Product Type: {loan.application.loan_product.product_type}")

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"  Duration Days: {loan.duration_days}")
print(f"  Duration Months: {loan.duration_days / 30}")

print(f"\nProduct Settings:")
print(f"  Interest Rate: {loan.application.loan_product.interest_rate}%")
print(f"  Processing Fee Rate: {loan.application.loan_product.processing_fee}%")

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

# Manual calculation
principal = loan.principal_amount
duration_days = loan.duration_days
months = Decimal(str(duration_days)) / Decimal('30')
interest_rate = loan.application.loan_product.interest_rate / Decimal('100')

print(f"\nManual Calculation:")
print(f"  Principal: {principal}")
print(f"  Duration: {duration_days} days")
print(f"  Months: {months}")
print(f"  Interest Rate: {loan.application.loan_product.interest_rate}% = {interest_rate}")

expected_interest = principal * interest_rate * months
print(f"\n  Expected Interest: {principal} × {interest_rate} × {months} = KES {expected_interest:,.2f}")
print(f"  Actual Interest: KES {loan.interest_amount:,.2f}")
print(f"  Match: {'✓ YES' if expected_interest == loan.interest_amount else '✗ NO'}")

if expected_interest != loan.interest_amount:
    difference = loan.interest_amount - expected_interest
    print(f"  Difference: KES {difference:,.2f}")

print(f"\n" + "=" * 80)
print("WHAT IT SHOULD BE (10% per month for 3 months)")
print("=" * 80)

correct_interest = principal * Decimal('0.10') * Decimal('3')
print(f"\n  Month 1: 10% of KES {principal:,.2f} = KES {principal * Decimal('0.10'):,.2f}")
print(f"  Month 2: 10% of KES {principal:,.2f} = KES {principal * Decimal('0.10'):,.2f}")
print(f"  Month 3: 10% of KES {principal:,.2f} = KES {principal * Decimal('0.10'):,.2f}")
print(f"  Total: KES {correct_interest:,.2f}")

if loan.interest_amount == correct_interest:
    print(f"\n✓ Interest is CORRECT!")
else:
    print(f"\n✗ Interest is WRONG!")
    print(f"  Should be: KES {correct_interest:,.2f}")
    print(f"  Currently: KES {loan.interest_amount:,.2f}")
