#!/usr/bin/env python
"""
Check penalty charges for a specific loan
"""
import os
import django

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

from loans.models import Loan
from decimal import Decimal

# Get the loan
loan = Loan.objects.filter(loan_number='LOAN-000001').first()

if not loan:
    print("Loan LOAN-000001 not found")
    exit(1)

print(f"\n=== Loan {loan.loan_number} Analysis ===")
print(f"Status: {loan.status}")
print(f"Disbursement Date: {loan.disbursement_date}")
print(f"Due Date: {loan.due_date}")
print(f"Duration: {loan.duration_days} days")
print(f"\n--- Amounts ---")
print(f"Principal: KES {loan.principal_amount:,.2f}")
print(f"Interest (stored): KES {loan.interest_amount:,.2f}")
print(f"Processing Fee (stored): KES {loan.processing_fee:,.2f}")
print(f"Total Amount (stored): KES {loan.total_amount:,.2f}")
print(f"\n--- Current Calculations ---")
print(f"Interest (calculated): KES {loan.get_display_interest_amount():,.2f}")
print(f"Processing Fee (calculated): KES {loan.get_display_processing_fee_amount():,.2f}")
print(f"Calculated Total: KES {loan.calculated_total_amount:,.2f}")
print(f"\n--- Payments & Penalties ---")
print(f"Amount Paid: KES {loan.amount_paid:,.2f}")
print(f"Total Penalties: KES {loan.total_penalties:,.2f}")
print(f"Outstanding Balance: KES {loan.outstanding_amount:,.2f}")

# Check penalty charges
print(f"\n--- Penalty Charges ---")
penalty_charges = loan.penalty_charges.all()
if penalty_charges.exists():
    for penalty in penalty_charges:
        print(f"  - {penalty.applied_date}: KES {penalty.amount:,.2f} (Rate: {penalty.penalty_rate}%, Days: {penalty.days_overdue})")
else:
    print("  No penalty charges found")

# Check if loan is overdue
print(f"\n--- Overdue Status ---")
print(f"Is Overdue: {loan.is_overdue}")
print(f"Days Overdue: {loan.days_overdue}")

# Check repayment method
print(f"\n--- Repayment Details ---")
print(f"Repayment Method: {loan.repayment_method}")

# Calculate what the outstanding should be
expected_outstanding = loan.calculated_total_amount - loan.amount_paid
print(f"\n--- Expected vs Actual ---")
print(f"Expected Outstanding (without penalties): KES {expected_outstanding:,.2f}")
print(f"Actual Outstanding: KES {loan.outstanding_amount:,.2f}")
print(f"Difference: KES {(loan.outstanding_amount - expected_outstanding):,.2f}")
