"""
Investigate LOAN-000114 to see what's wrong with the total calculation
"""
import os
import sys

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

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

from loans.models import Loan
from decimal import Decimal

print(f"\n{'='*80}")
print(f"INVESTIGATING LOAN-000114")
print(f"{'='*80}\n")

try:
    loan = Loan.objects.get(loan_number='LOAN-000114')
    
    print(f"Loan: {loan.loan_number}")
    print(f"Borrower: {loan.borrower.get_full_name()}")
    print(f"Product: {loan.application.loan_product.name}")
    print(f"Created: {loan.created_at}")
    
    print(f"\nVALUES IN DATABASE:")
    print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
    print(f"  Interest:        KES {loan.interest_amount:>12,.2f}")
    print(f"  Processing Fee:  KES {loan.processing_fee:>12,.2f}")
    print(f"  Total:           KES {loan.total_amount:>12,.2f}")
    
    # Calculate what total SHOULD be
    correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
    
    print(f"\nCALCULATION CHECK:")
    print(f"  {loan.principal_amount:,.2f} + {loan.interest_amount:,.2f} + {loan.processing_fee:,.2f}")
    print(f"  = KES {correct_total:,.2f}")
    
    print(f"\nCOMPARISON:")
    print(f"  Database Total:   KES {loan.total_amount:>12,.2f}")
    print(f"  Calculated Total: KES {correct_total:>12,.2f}")
    print(f"  Difference:       KES {correct_total - loan.total_amount:>12,.2f}")
    
    if abs(loan.total_amount - correct_total) > Decimal('0.01'):
        print(f"\n❌ TOTAL IS WRONG!")
        print(f"   The total_amount field does NOT equal principal + interest + processing_fee")
        print(f"   This is a bug in the loan creation code!")
        
        # Check the application
        print(f"\nLOAN APPLICATION VALUES:")
        print(f"  Application: {loan.application.application_number}")
        print(f"  Requested Amount:   KES {loan.application.requested_amount:>12,.2f}")
        print(f"  Interest Amount:    KES {loan.application.interest_amount:>12,.2f}")
        print(f"  Processing Fee:     KES {loan.application.processing_fee_amount:>12,.2f}")
        print(f"  Total Amount:       KES {loan.application.total_amount:>12,.2f}")
        
        app_correct_total = loan.application.requested_amount + loan.application.interest_amount + loan.application.processing_fee_amount
        print(f"\n  Application Calculated Total: KES {app_correct_total:,.2f}")
        
        if abs(loan.application.total_amount - app_correct_total) > Decimal('0.01'):
            print(f"  ❌ Application total is also wrong!")
        else:
            print(f"  ✅ Application total is correct")
        
        # Fix it
        print(f"\n{'='*80}")
        print(f"FIXING LOAN-000114")
        print(f"{'='*80}\n")
        
        loan.total_amount = correct_total
        loan.save()
        print(f"✅ Fixed loan total: {loan.total_amount:,.2f}")
        
        if abs(loan.application.total_amount - app_correct_total) > Decimal('0.01'):
            loan.application.total_amount = app_correct_total
            loan.application.save()
            print(f"✅ Fixed application total: {loan.application.total_amount:,.2f}")
        
        print(f"\n✅ LOAN-000114 HAS BEEN FIXED!")
    else:
        print(f"\n✅ Total is correct!")
    
    print(f"\n{'='*80}\n")
    
except Loan.DoesNotExist:
    print(f"❌ Loan LOAN-000114 not found")
    sys.exit(1)
except Exception as e:
    print(f"\n❌ ERROR: {str(e)}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
