#!/usr/bin/env python
import os
import sys
import django

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

from loans.models import Loan, Repayment
from users.models import CustomUser
from reports.enhanced_models import CustomerRequest, RegistrationFeePayment
from django.db.models import Sum, Count
from decimal import Decimal

print("=== DASHBOARD DATA DIAGNOSTIC ===")
print()

# Check total loans
total_loans = Loan.objects.count()
print(f"Total loans in database: {total_loans}")

if total_loans > 0:
    # Check loan statuses
    status_counts = Loan.objects.values('status').annotate(count=Count('id'))
    print("\nLoan status breakdown:")
    for status in status_counts:
        print(f"  {status['status']}: {status['count']}")
    
    # Check active loans specifically
    active_loans = Loan.objects.filter(status='active')
    active_count = active_loans.count()
    print(f"\nActive loans: {active_count}")
    
    if active_count > 0:
        # Check active loan details
        active_loan_data = active_loans.aggregate(
            total_principal=Sum('principal_amount'),
            total_amount=Sum('total_amount'),
            total_paid=Sum('_amount_paid_cache')
        )
        print(f"Active loans - Total principal: {active_loan_data['total_principal']}")
        print(f"Active loans - Total amount: {active_loan_data['total_amount']}")
        print(f"Active loans - Total paid: {active_loan_data['total_paid']}")
        
        # Check individual loan data
        print("\nFirst 5 active loans:")
        for loan in active_loans[:5]:
            print(f"  Loan {loan.loan_number}: Principal={loan.principal_amount}, Total={loan.total_amount}, Paid={loan.amount_paid}, Status={loan.status}")
    
    # Check all loan statuses (in case there's a case sensitivity issue)
    print("\nAll unique status values in database:")
    unique_statuses = Loan.objects.values_list('status', flat=True).distinct()
    for status in unique_statuses:
        print(f"  '{status}'")
else:
    print("No loans found in database!")

# Check repayments
repayment_count = Repayment.objects.count()
print(f"\nTotal repayments: {repayment_count}")

# Check customer requests
customer_requests = CustomerRequest.objects.count()
print(f"Total customer requests: {customer_requests}")

# Check registration fee payments
reg_payments = RegistrationFeePayment.objects.count()
print(f"Total registration fee payments: {reg_payments}")

print("\n=== END DIAGNOSTIC ===")