#!/usr/bin/env python
"""
Test loan officer dashboard branch filtering
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import RequestFactory, Client
from django.contrib.auth import get_user_model
from utils.views import notifications

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=== Testing Dashboard for {loan_officer.get_full_name()} ===")
print(f"Branch: {loan_officer.branch.name}")

# Create a test client and login
client = Client()
client.force_login(loan_officer)

# Access the notifications/dashboard page
response = client.get('/utils/notifications/')

print(f"\nResponse status: {response.status_code}")

if response.status_code == 200:
    context = response.context
    
    if 'pending_applications' in context:
        pending_apps = context['pending_applications']
        print(f"\nPending Applications shown: {len(pending_apps)}")
        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 if any are from wrong branch
        wrong_branch = [app for app in pending_apps if app.borrower.branch != loan_officer.branch]
        if wrong_branch:
            print(f"\n❌ ERROR: Showing {len(wrong_branch)} applications from other branches!")
        else:
            print(f"\n✓ SUCCESS: All applications are from {loan_officer.branch.name}")
    else:
        print("\nNo pending_applications in context (might not be staff user)")
    
    if 'loan_statistics' in context:
        stats = context['loan_statistics']
        print(f"\nLoan Statistics:")
        print(f"  - Total Disbursed: KES {stats['total_disbursed']:,.2f}")
        print(f"  - Active Loans: {stats['active_loans']}")
        print(f"  - Defaulted Loans: {stats['defaulted_loans']}")
    
    if 'user_statistics' in context:
        stats = context['user_statistics']
        print(f"\nUser Statistics:")
        print(f"  - Total Users: {stats['total_users']}")
        print(f"  - Active Users: {stats['active_users']}")
else:
    print(f"Failed to access dashboard: {response.status_code}")
