import os
import django

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

from loans.models import LoanApplication
from users.models import CustomUser

# Get all applications
apps = LoanApplication.objects.all()
print(f"Total applications in DB: {apps.count()}")

for app in apps:
    print(f"  {app.application_number} - {app.borrower.get_full_name()} - Branch: {app.borrower.branch.name if app.borrower.branch else 'None'} - Status: {app.status}")

# Check admin user
admin = CustomUser.objects.get(username='admin')
print(f"\nAdmin branch: {admin.branch.name if admin.branch else 'None'}")
print(f"Admin role: {admin.role}")
print(f"Admin is_superuser: {admin.is_superuser}")

# Simulate the query from loans view
from django.db.models import Q

loans_list = LoanApplication.objects.all().select_related(
    'borrower',
    'loan_product',
    'loan'
).prefetch_related(
    'loan__repayments'
).filter(
    Q(loan__isnull=True) | Q(loan__is_deleted=False)
)

print(f"\nAfter base filter: {loans_list.count()} applications")

# Check if admin would see them
if admin.role in ['loan_officer', 'team_leader'] and not admin.is_superuser:
    loans_list = loans_list.filter(borrower__portfolio_manager=admin)
    print(f"After loan officer filter: {loans_list.count()}")
elif admin.role in ['secretary', 'auditor'] and not admin.is_superuser:
    if admin.branch:
        loans_list = loans_list.filter(borrower__branch=admin.branch)
        print(f"After secretary filter: {loans_list.count()}")
else:
    print("Admin/Manager - should see all")

print(f"\nFinal count: {loans_list.count()}")
