"""
Quick script to check what data exists in the database
"""
import os
import django

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

from loans.models import Loan
from users.models import CustomUser, Branch
from django.db.models import Count, Sum

print("=" * 60)
print("DATABASE DATA CHECK")
print("=" * 60)

# Check branches
print("\n📍 BRANCHES:")
branches = Branch.objects.all()
for branch in branches:
    print(f"  - {branch.name} (ID: {branch.id})")

# Check users/borrowers
print("\n👥 USERS:")
users_by_role = CustomUser.objects.values('role').annotate(count=Count('id'))
for item in users_by_role:
    print(f"  - {item['role']}: {item['count']}")

# Check loans
print("\n💰 LOANS:")
total_loans = Loan.objects.count()
print(f"  Total Loans: {total_loans}")

if total_loans > 0:
    loans_by_status = Loan.objects.values('status').annotate(count=Count('id'))
    print("\n  By Status:")
    for item in loans_by_status:
        print(f"    - {item['status']}: {item['count']}")
    
    loans_by_branch = Loan.objects.select_related('borrower__branch').values(
        'borrower__branch__name'
    ).annotate(count=Count('id'))
    print("\n  By Branch:")
    for item in loans_by_branch:
        branch_name = item['borrower__branch__name'] or 'No Branch'
        print(f"    - {branch_name}: {item['count']}")
    
    # Check active loans
    active_loans = Loan.objects.filter(
        status__in=['active', 'approved', 'disbursed'],
        is_deleted=False
    )
    print(f"\n  Active Loans (not deleted): {active_loans.count()}")
    
    # Sample loan details
    print("\n  Sample Loans:")
    for loan in Loan.objects.all()[:5]:
        branch_name = loan.borrower.branch.name if loan.borrower and loan.borrower.branch else 'No Branch'
        print(f"    - Loan #{loan.loan_number}: {loan.status}, Branch: {branch_name}, Deleted: {loan.is_deleted}")

print("\n" + "=" * 60)
