"""
Fix amortization schedule calculation and days overdue logic
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal
from datetime import datetime

# Get the specific loan
loan = Loan.objects.get(loan_number='LOAN-000036')

print(f"\n=== Loan {loan.loan_number} Analysis ===")
print(f"Borrower: {loan.borrower.get_full_name()}")
print(f"Status: {loan.status}")
print(f"Disbursement Date: {loan.disbursement_date}")
print(f"Due Date: {loan.due_date}")
print(f"Today: {datetime.now().date()}")

# Check if overdue
print(f"\nIs Overdue: {loan.is_overdue}")
print(f"Days Overdue: {loan.days_overdue}")

# Calculate correct values
principal = loan.principal_amount
interest = loan.get_display_interest_amount()
processing_fee = loan.get_display_processing_fee_amount()

print(f"\n=== Loan Amounts ===")
print(f"Principal Amount: KES {principal}")
print(f"Interest Amount: KES {interest}")
print(f"Processing Fee: KES {processing_fee}")
print(f"Total Amount: KES {principal + interest + processing_fee}")

# Check repayments
from loans.models import Repayment
repayments = Repayment.objects.filter(loan=loan).order_by('payment_date')
total_paid = sum(r.amount for r in repayments)

print(f"\n=== Repayments ===")
print(f"Number of Repayments: {repayments.count()}")
print(f"Total Paid: KES {total_paid}")
for r in repayments:
    print(f"  - {r.payment_date}: KES {r.amount} ({r.payment_method})")

# Calculate outstanding
outstanding = principal + interest + processing_fee - total_paid
print(f"\nOutstanding Balance: KES {outstanding}")
print(f"Loan Outstanding Amount: KES {loan.outstanding_amount}")

# Check amortization schedule
schedule = loan.get_amortization_schedule()
print(f"\n=== Amortization Schedule ===")
print(f"Number of Payments: {len(schedule)}")
print(f"First Payment:")
first = schedule[0]
print(f"  Payment Date: {first['payment_date']}")
print(f"  Beginning Balance: KES {first['beginning_balance']}")
print(f"  Scheduled Payment: KES {first['scheduled_payment']}")
print(f"  Principal: KES {first['principal']}")
print(f"  Interest: KES {first['interest']}")
print(f"  Processing Fee: KES {first['processing_fee']}")
print(f"  Ending Balance: KES {first['ending_balance']}")

# Check if due date is in the past
from datetime import date
today = date.today()
if loan.due_date:
    days_diff = (today - loan.due_date).days
    print(f"\n=== Due Date Analysis ===")
    print(f"Due Date: {loan.due_date}")
    print(f"Today: {today}")
    print(f"Days Difference: {days_diff}")
    if days_diff > 0:
        print(f"Loan is {days_diff} days overdue")
    else:
        print(f"Loan is NOT overdue (due in {abs(days_diff)} days)")
