#!/usr/bin/env python
"""
Verify Processing Fee Fix in Production

Run this script on the production server after deploying the fix
to verify that the processing fees report is now showing correct data.
"""
import os
import django

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

from loans.models import Loan
from decimal import Decimal

def verify_fix():
    print("\n" + "="*80)
    print("PROCESSING FEE REPORT FIX VERIFICATION")
    print("="*80)
    
    # Check for LOAN-000086 specifically
    loan_086 = Loan.objects.filter(loan_number='LOAN-000086').first()
    
    if loan_086:
        print("\n✓ Found LOAN-000086")
        print("-" * 80)
        print(f"Borrower: {loan_086.borrower.first_name} {loan_086.borrower.last_name}")
        print(f"Phone: {loan_086.borrower.phone_number}")
        print(f"Principal Amount: KES {loan_086.principal_amount:,.2f}")
        print(f"Processing Fee (stored): KES {loan_086.processing_fee:,.2f}")
        
        if loan_086.application and loan_086.application.loan_product:
            product = loan_086.application.loan_product
            print(f"Product: {product.name}")
            print(f"Product Type: {product.product_type}")
            print(f"Fee Rate: {product.get_processing_fee()}%")
            
            # Calculate what it should be
            expected_fee = loan_086.principal_amount * Decimal(str(product.get_processing_fee())) / Decimal('100')
            print(f"Expected Fee: KES {expected_fee:,.2f}")
            
            # What the old code would have calculated
            old_calculation = loan_086.principal_amount * Decimal('0.02')
            print(f"\nOld (incorrect) calculation (2%): KES {old_calculation:,.2f}")
            print(f"New (correct) value: KES {loan_086.processing_fee:,.2f}")
            
            if abs(loan_086.processing_fee - expected_fee) < Decimal('0.01'):
                print("\n✅ VERIFICATION PASSED: Processing fee is correct!")
            else:
                print(f"\n⚠️  WARNING: Processing fee mismatch!")
                print(f"   Stored: KES {loan_086.processing_fee:,.2f}")
                print(f"   Expected: KES {expected_fee:,.2f}")
        else:
            print("\n⚠️  No loan product found for this loan")
    else:
        print("\n⚠️  LOAN-000086 not found in database")
        print("This might be expected if testing on a different environment")
    
    # Check a sample of other loans
    print("\n" + "="*80)
    print("SAMPLE OF OTHER LOANS")
    print("="*80)
    
    loans = Loan.objects.filter(status='active').select_related(
        'borrower', 'application__loan_product'
    ).order_by('-created_at')[:5]
    
    print(f"\n{'Loan':<15} {'Borrower':<25} {'Product':<20} {'Principal':>15} {'Fee':>15} {'Rate':>8}")
    print("-" * 80)
    
    for loan in loans:
        borrower_name = f"{loan.borrower.first_name} {loan.borrower.last_name}"
        product_name = loan.application.loan_product.name if loan.application and loan.application.loan_product else 'N/A'
        fee_rate = loan.application.loan_product.get_processing_fee() if loan.application and loan.application.loan_product else 0
        
        print(f"{loan.loan_number:<15} {borrower_name[:25]:<25} {product_name[:20]:<20} "
              f"KES {loan.principal_amount:>11,.2f} KES {loan.processing_fee:>11,.2f} {fee_rate:>6.1f}%")
    
    print("-" * 80)
    
    # Summary
    print("\n" + "="*80)
    print("VERIFICATION SUMMARY")
    print("="*80)
    print("\n✓ The fix ensures:")
    print("  1. Processing fees use actual loan.processing_fee values")
    print("  2. Product names show actual loan product names")
    print("  3. Fee rates display actual product rates")
    print("\n✓ The report at /reports/processing-fees/ should now show correct data")
    print("\n" + "="*80 + "\n")

if __name__ == '__main__':
    verify_fix()
