"""
Test script to verify branch and portfolio filtering
"""
import os
import django

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

from users.models import CustomUser, Branch
from loans.models import Loan, LoanApplication, Repayment
from utils.filtering import (
    get_filtered_clients,
    get_filtered_loans,
    get_filtered_applications,
    get_filtered_repayments,
    get_user_context
)


def test_filtering():
    print("\n" + "="*60)
    print("TESTING BRANCH AND PORTFOLIO FILTERING")
    print("="*60)
    
    # Test with different user roles
    test_users = [
        ('admin', 'Admin User'),
        ('loan_officer', 'Loan Officer'),
        ('secretary', 'Secretary'),
        ('auditor', 'Auditor'),
    ]
    
    for role, description in test_users:
        print(f"\n{'-'*60}")
        print(f"Testing as: {description} ({role})")
        print(f"{'-'*60}")
        
        # Get a user with this role
        user = CustomUser.objects.filter(role=role, is_active=True).first()
        
        if not user:
            print(f"⚠ No {role} user found, skipping")
            continue
        
        # Get user context
        context = get_user_context(user)
        print(f"User: {user.get_full_name()} ({user.email})")
        print(f"Branch: {context['branch_name'] or 'None'}")
        print(f"Is Portfolio Manager: {context['is_portfolio_manager']}")
        
        # Test client filtering
        clients = get_filtered_clients(user)
        print(f"\nClients visible: {clients.count()}")
        
        # Test loan filtering
        loans = get_filtered_loans(user)
        print(f"Loans visible: {loans.count()}")
        
        # Test application filtering
        applications = get_filtered_applications(user)
        print(f"Applications visible: {applications.count()}")
        
        # Test repayment filtering
        repayments = get_filtered_repayments(user)
        print(f"Repayments visible: {repayments.count()}")
        
        # Test with branch selection
        if context['branch_id']:
            print(f"\nWith branch filter ({context['branch_name']}):")
            clients_branch = get_filtered_clients(user, context['branch_id'])
            loans_branch = get_filtered_loans(user, context['branch_id'])
            print(f"  Clients: {clients_branch.count()}")
            print(f"  Loans: {loans_branch.count()}")
    
    print("\n" + "="*60)
    print("FILTERING TEST COMPLETE")
    print("="*60 + "\n")


if __name__ == '__main__':
    test_filtering()
