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 loan with 56000 total amount
loans = Loan.objects.filter(
    principal_amount=50000,
    total_amount=56000
).select_related('application', 'application__loan_product', 'borrower')

print(f"\nFound {loans.count()} loan(s) with principal 50000 and total 56000\n")

for loan in loans:
    print(f"{'='*60}")
    print(f"Loan: {loan.loan_number}")
    print(f"Borrower: {loan.borrower.get_full_name()}")
    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 part of the calculation
    if abs(difference - processing_fee) < Decimal('0.01'):
        print(f"\n⚠️  ISSUE: Total amount is missing the processing fee!")
    elif abs(difference - interest) < Decimal('0.01'):
        print(f"\n⚠️  ISSUE: Total amount is missing the interest!")
    else:
        print(f"\n⚠️  ISSUE: Total amount calculation is incorrect!")
    
    # Fix the loan
    print(f"\n{'='*60}")
    print(f"FIXING THE LOAN")
    print(f"{'='*60}\n")
    
    old_total = loan.total_amount
    loan.total_amount = correct_total
    loan.save()
    
    print(f"✅ Loan {loan.loan_number} has been fixed!")
    print(f"  Old total_amount: KES {old_total:,.2f}")
    print(f"  New total_amount: KES {loan.total_amount:,.2f}")
    print(f"  Difference: KES {correct_total - old_total:,.2f}\n")

if loans.count() == 0:
    print("No loans found with the specified criteria.")
    print("\nSearching for all active loans with potential issues...")
    
    all_loans = Loan.objects.filter(status='active').select_related('application', 'application__loan_product', 'borrower')
    
    issues_found = 0
    for loan in all_loans:
        correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        if abs(loan.total_amount - correct_total) > Decimal('0.01'):
            issues_found += 1
            print(f"\n{loan.loan_number}: Expected {correct_total:,.2f}, Got {loan.total_amount:,.2f}")
            
            # Fix it
            loan.total_amount = correct_total
            loan.save()
            print(f"  ✅ Fixed!")
    
    if issues_found == 0:
        print("No issues found in active loans.")
    else:
        print(f"\n✅ Fixed {issues_found} loan(s) with incorrect total_amount")
