#!/usr/bin/env python
"""
Debug loan officer branch filtering
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model
from loans.models import LoanApplication, Loan
from users.models import Branch

User = get_user_model()

# Get the loan officer
loan_officer = User.objects.filter(email='loan_officer_ksm@example.com').first()

if not loan_officer:
    print("Loan officer not found")
    exit(1)

print(f"\n=== Loan Officer Details ===")
print(f"Name: {loan_officer.get_full_name()}")
print(f"Email: {loan_officer.email}")
print(f"Role: {loan_officer.role}")
print(f"Branch: {loan_officer.branch.name if loan_officer.branch else 'No branch assigned'}")
print(f"Branch ID: {loan_officer.branch.id if loan_officer.branch else 'N/A'}")

# Check all applications
print(f"\n=== All Loan Applications ===")
all_apps = LoanApplication.objects.all()
print(f"Total applications: {all_apps.count()}")
for app in all_apps:
    borrower_branch = app.borrower.branch.name if app.borrower.branch else "No branch"
    print(f"  - {app.application_number}: {app.borrower.get_full_name()} (Branch: {borrower_branch}, Status: {app.status})")

# Check what the loan officer should see
print(f"\n=== Applications Loan Officer SHOULD See ===")
if loan_officer.branch:
    branch_apps = LoanApplication.objects.filter(borrower__branch=loan_officer.branch)
    print(f"Applications in {loan_officer.branch.name}: {branch_apps.count()}")
    for app in branch_apps:
        print(f"  - {app.application_number}: {app.borrower.get_full_name()} (Status: {app.status})")
else:
    print("Loan officer has no branch assigned")

# Check pending applications
print(f"\n=== Pending Applications ===")
pending_apps = LoanApplication.objects.filter(status='pending')
print(f"Total pending: {pending_apps.count()}")
for app in pending_apps:
    borrower_branch = app.borrower.branch.name if app.borrower.branch else "No branch"
    print(f"  - {app.application_number}: {app.borrower.get_full_name()} (Branch: {borrower_branch})")

# Check all users
print(f"\n=== All Users/Borrowers ===")
all_users = User.objects.filter(role='borrower')
print(f"Total borrowers: {all_users.count()}")
for user in all_users:
    branch_name = user.branch.name if user.branch else "No branch"
    print(f"  - {user.get_full_name()} ({user.phone_number}) - Branch: {branch_name}")

# Check loans
print(f"\n=== Active Loans ===")
active_loans = Loan.objects.filter(status='active', is_deleted=False)
print(f"Total active loans: {active_loans.count()}")
for loan in active_loans:
    borrower_branch = loan.borrower.branch.name if loan.borrower.branch else "No branch"
    print(f"  - {loan.loan_number}: {loan.borrower.get_full_name()} (Branch: {borrower_branch})")
