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 django.contrib.auth import get_user_model
User = get_user_model()

# Search for users with "Phin" in their name
users = User.objects.filter(first_name__icontains='Phin')

print(f"\nFound {users.count()} user(s) with 'Phin' in name:\n")

for user in users:
    print(f"User: {user.get_full_name()} ({user.phone_number})")
    
    loans = Loan.objects.filter(borrower=user).select_related('application', 'application__loan_product').order_by('-created_at')
    
    print(f"  Has {loans.count()} loan(s)\n")
    
    for loan in loans:
        print(f"  {'='*66}")
        print(f"  Loan: {loan.loan_number} | Status: {loan.status}")
        print(f"  {'='*66}")
        
        print(f"  Principal:       KES {loan.principal_amount:,.2f}")
        print(f"  Interest:        KES {loan.interest_amount:,.2f}")
        print(f"  Processing Fee:  KES {loan.processing_fee:,.2f}")
        print(f"  Total (DB):      KES {loan.total_amount:,.2f}")
        
        # Calculate correct total
        correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        print(f"  Total (Calc):    KES {correct_total:,.2f}")
        
        if abs(loan.total_amount - correct_total) > Decimal('0.01'):
            print(f"  ❌ MISMATCH! Difference: KES {correct_total - loan.total_amount:,.2f}")
            
            # Fix it
            loan.total_amount = correct_total
            loan.save()
            print(f"  ✅ FIXED!")
        else:
            print(f"  ✅ Correct")
        
        print()

# Also check all loans with principal 50000
print(f"\n{'='*70}")
print("Checking all loans with principal amount = 50,000")
print(f"{'='*70}\n")

loans_50k = Loan.objects.filter(principal_amount=50000).select_related('borrower', 'application', 'application__loan_product')

for loan in loans_50k:
    correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
    
    if abs(loan.total_amount - correct_total) > Decimal('0.01'):
        print(f"{loan.loan_number} ({loan.borrower.get_full_name()})")
        print(f"  Principal: {loan.principal_amount:,.2f}")
        print(f"  Interest: {loan.interest_amount:,.2f}")
        print(f"  Processing Fee: {loan.processing_fee:,.2f}")
        print(f"  Total (DB): {loan.total_amount:,.2f}")
        print(f"  Total (Correct): {correct_total:,.2f}")
        print(f"  ❌ Fixing...")
        
        loan.total_amount = correct_total
        loan.save()
        print(f"  ✅ Fixed!\n")
