"""
Check why amount_paid is showing 0 for loans that have payments
"""
import os
import django

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

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

def check_amount_paid_issue():
    """Check why amount_paid is showing 0"""
    
    print("=" * 80)
    print("CHECKING AMOUNT_PAID ISSUE")
    print("=" * 80)
    
    # Get the specific loans mentioned
    loan_numbers = ['LOAN-000128', 'LOAN-000127', 'LOAN-000110', 'LOAN-000109', 'LOAN-000096']
    
    for loan_number in loan_numbers:
        print(f"\n{'=' * 80}")
        print(f"Checking {loan_number}")
        print("=" * 80)
        
        try:
            loan = Loan.objects.get(loan_number=loan_number)
            
            print(f"\n1. Loan Details:")
            print(f"   - ID: {loan.id}")
            print(f"   - Status: {loan.status}")
            print(f"   - Is Deleted: {loan.is_deleted}")
            print(f"   - Is Rolled Over: {loan.is_rolled_over}")
            print(f"   - Total Amount: KSh {loan.total_amount:,.2f}")
            
            # Check repayments using the related manager
            print(f"\n2. Repayments (using loan.repayments):")
            repayments = loan.repayments.all()
            print(f"   - Count: {repayments.count()}")
            
            if repayments.exists():
                total_from_manager = Decimal('0.00')
                for rep in repayments:
                    print(f"   - Repayment {rep.id}: KSh {rep.amount:,.2f} on {rep.payment_date}")
                    total_from_manager += rep.amount
                print(f"   - Total from manager: KSh {total_from_manager:,.2f}")
            
            # Check using aggregate
            print(f"\n3. Repayments (using aggregate):")
            total_aggregate = loan.repayments.aggregate(total=Sum('amount'))['total']
            print(f"   - Total from aggregate: KSh {total_aggregate:,.2f}" if total_aggregate else "   - Total from aggregate: KSh 0.00")
            
            # Check using direct query
            print(f"\n4. Repayments (using direct query):")
            direct_repayments = Repayment.objects.filter(loan=loan)
            print(f"   - Count: {direct_repayments.count()}")
            
            if direct_repayments.exists():
                total_direct = Decimal('0.00')
                for rep in direct_repayments:
                    print(f"   - Repayment {rep.id}: KSh {rep.amount:,.2f} on {rep.payment_date}")
                    total_direct += rep.amount
                print(f"   - Total from direct query: KSh {total_direct:,.2f}")
            
            # Check using the property
            print(f"\n5. Using loan.amount_paid property:")
            try:
                amount_paid = loan.amount_paid
                print(f"   - Amount Paid: KSh {amount_paid:,.2f}")
            except Exception as e:
                print(f"   - Error: {str(e)}")
            
            # Check outstanding
            print(f"\n6. Using loan.outstanding_amount property:")
            try:
                outstanding = loan.outstanding_amount
                print(f"   - Outstanding: KSh {outstanding:,.2f}")
            except Exception as e:
                print(f"   - Error: {str(e)}")
            
        except Loan.DoesNotExist:
            print(f"   ❌ Loan {loan_number} not found")
        except Exception as e:
            print(f"   ❌ Error: {str(e)}")
            import traceback
            traceback.print_exc()
    
    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    
    # Check all loans with repayments
    loans_with_repayments = Loan.objects.filter(
        repayments__isnull=False
    ).distinct()
    
    print(f"\nTotal loans with repayments: {loans_with_repayments.count()}")
    
    # Check total repayments
    total_repayments = Repayment.objects.count()
    print(f"Total repayment records: {total_repayments}")
    
    # Check if there's a mismatch
    print("\nChecking for calculation issues...")
    issues_found = 0
    
    for loan in Loan.objects.filter(status='active', is_deleted=False)[:10]:
        repayment_count = loan.repayments.count()
        amount_paid = loan.amount_paid
        
        if repayment_count > 0 and amount_paid == 0:
            issues_found += 1
            print(f"   ❌ {loan.loan_number}: Has {repayment_count} repayments but amount_paid = 0")
    
    if issues_found == 0:
        print("   ✅ No calculation issues found")
    else:
        print(f"\n   ❌ Found {issues_found} loans with calculation issues")
    
    print("\n" + "=" * 80)

if __name__ == '__main__':
    check_amount_paid_issue()
