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 all loans for Phin Client
from django.contrib.auth import get_user_model
User = get_user_model()

try:
    phin = User.objects.get(phone_number='+254114565176')
    print(f"\nFound user: {phin.get_full_name()} ({phin.phone_number})")
    
    loans = Loan.objects.filter(borrower=phin).select_related('application', 'application__loan_product').order_by('-created_at')
    
    print(f"\nFound {loans.count()} loan(s) for this user:\n")
    
    for loan in loans:
        print(f"{'='*70}")
        print(f"Loan Number: {loan.loan_number}")
        print(f"Status: {loan.status}")
        print(f"Created: {loan.created_at}")
        print(f"{'='*70}")
        
        print(f"\nStored in Database:")
        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 Amount:    KES {loan.total_amount:,.2f}")
        print(f"  Duration:        {loan.duration_days} days")
        
        # Calculate correct total
        correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        
        print(f"\nCalculated Total:")
        print(f"  {loan.principal_amount:,.2f} + {loan.interest_amount:,.2f} + {loan.processing_fee:,.2f} = {correct_total:,.2f}")
        
        if abs(loan.total_amount - correct_total) > Decimal('0.01'):
            print(f"\n❌ MISMATCH FOUND!")
            print(f"  Database shows: KES {loan.total_amount:,.2f}")
            print(f"  Should be:      KES {correct_total:,.2f}")
            print(f"  Difference:     KES {correct_total - loan.total_amount:,.2f}")
            
            # Fix it
            print(f"\n  Fixing...")
            loan.total_amount = correct_total
            loan.save()
            print(f"  ✅ Fixed! New total: KES {loan.total_amount:,.2f}")
        else:
            print(f"\n✅ Total amount is correct!")
        
        print(f"\nLoan Product: {loan.application.loan_product.name}")
        print(f"  Type: {loan.application.loan_product.product_type}")
        print(f"  Interest Rate: {loan.application.loan_product.interest_rate}%")
        print(f"  Processing Fee: {loan.application.loan_product.processing_fee}%")
        print()

except User.DoesNotExist:
    print("User with phone +254114565176 not found")
