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 loan 113
try:
    loan = Loan.objects.get(loan_number='LOAN-000113')
    
    print(f"\n{'='*60}")
    print(f"LOAN-000113 CALCULATION ANALYSIS")
    print(f"{'='*60}\n")
    
    print(f"Database Values:")
    print(f"  Principal Amount: KES {loan.principal_amount:,.2f}")
    print(f"  Interest Amount:  KES {loan.interest_amount:,.2f}")
    print(f"  Processing Fee:   KES {loan.processing_fee:,.2f}")
    print(f"  Total Amount:     KES {loan.total_amount:,.2f}")
    print(f"  Duration:         {loan.duration_days} days")
    
    print(f"\nLoan Product: {loan.application.loan_product.name}")
    print(f"  Product Type: {loan.application.loan_product.product_type}")
    print(f"  Interest Rate: {loan.application.loan_product.interest_rate}%")
    print(f"  Processing Fee Rate: {loan.application.loan_product.processing_fee}%")
    
    # Calculate what it SHOULD be
    principal = loan.principal_amount
    interest = loan.interest_amount
    processing_fee = loan.processing_fee
    
    correct_total = principal + interest + processing_fee
    
    print(f"\nCorrect Calculation:")
    print(f"  {principal:,.2f} + {interest:,.2f} + {processing_fee:,.2f} = {correct_total:,.2f}")
    
    print(f"\nDifference:")
    difference = correct_total - loan.total_amount
    print(f"  Expected: KES {correct_total:,.2f}")
    print(f"  Actual:   KES {loan.total_amount:,.2f}")
    print(f"  Missing:  KES {difference:,.2f}")
    
    # Check if it's missing the processing fee
    if abs(difference - processing_fee) < Decimal('0.01'):
        print(f"\n⚠️  ISSUE FOUND: Total amount is missing the processing fee!")
        print(f"  The total_amount field = principal + interest (missing + processing_fee)")
    
    # Check using display methods
    print(f"\nUsing Display Methods (current system rates):")
    display_interest = loan.get_display_interest_amount()
    display_processing_fee = loan.get_display_processing_fee_amount()
    display_total = principal + display_interest + display_processing_fee
    
    print(f"  Interest (display):  KES {display_interest:,.2f}")
    print(f"  Processing Fee (display): KES {display_processing_fee:,.2f}")
    print(f"  Total (display):     KES {display_total:,.2f}")
    
    # Fix the loan
    print(f"\n{'='*60}")
    print(f"FIXING THE LOAN")
    print(f"{'='*60}\n")
    
    loan.total_amount = correct_total
    loan.save()
    
    print(f"✅ Loan LOAN-000113 has been fixed!")
    print(f"  New total_amount: KES {loan.total_amount:,.2f}")
    
except Loan.DoesNotExist:
    print("Loan LOAN-000113 not found")
