"""
Debug paid amount mismatches
"""
import os
import sys
import django

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from decimal import Decimal
from loans.models import Loan, Repayment
from django.db.models import Sum

print("=" * 80)
print("DEBUGGING PAID AMOUNT MISMATCHES")
print("=" * 80)

active_loans = Loan.objects.filter(status='active', is_deleted=False)

print(f"\nChecking {active_loans.count()} active loans...")
print(f"\n{'Loan':<20} {'Repayments (DB)':<18} {'Paid (Property)':<18} {'Difference'}")
print("-" * 80)

total_mismatch = Decimal('0')

for loan in active_loans:
    # Direct from repayments table
    paid_db = Repayment.objects.filter(loan=loan).aggregate(
        total=Sum('amount')
    )['total'] or Decimal('0')
    
    # From loan property (which uses LoanCalculationService)
    paid_prop = loan.amount_paid
    
    diff = paid_db - paid_prop
    
    if abs(diff) > Decimal('0.01'):
        print(f"{loan.loan_number:<20} KES {paid_db:>13,.2f}  KES {paid_prop:>13,.2f}  "
              f"KES {diff:>13,.2f} ⚠️")
        total_mismatch += diff

print("-" * 80)
print(f"Total Mismatch: KES {total_mismatch:>13,.2f}")

print(f"\n{'=' * 80}")
print("ANALYSIS")
print(f"{'=' * 80}")

if abs(total_mismatch) < Decimal('0.01'):
    print("\n✅ All loans have matching paid amounts!")
else:
    print(f"\n⚠️  Total paid amount mismatch: KES {total_mismatch:,.2f}")
    print("\nThis explains the aging report difference:")
    print(f"  Aging uses: Repayment.sum()")
    print(f"  Property uses: LoanCalculationService (may exclude some repayments)")

print(f"\n{'=' * 80}\n")
