"""
Verification script to ensure filtering is properly implemented
"""
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,
    apply_branch_and_portfolio_filters
)


def verify_imports():
    """Verify that filtering module is properly imported in all view files"""
    print("\n" + "="*60)
    print("VERIFYING FILTERING IMPORTS")
    print("="*60)
    
    files_to_check = [
        'reports/views.py',
        'loans/views.py',
        'utils/views.py',
        'users/views.py',
    ]
    
    all_good = True
    
    for file_path in files_to_check:
        if not os.path.exists(file_path):
            print(f"⚠ {file_path} not found")
            continue
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        if 'from utils.filtering import' in content:
            print(f"✓ {file_path} - Filtering imports found")
        else:
            print(f"✗ {file_path} - Filtering imports MISSING")
            all_good = False
    
    return all_good


def verify_filtering_functions():
    """Verify that filtering functions work correctly"""
    print("\n" + "="*60)
    print("VERIFYING FILTERING FUNCTIONS")
    print("="*60)
    
    try:
        # Test with admin user
        admin = CustomUser.objects.filter(role='admin', is_active=True).first()
        if admin:
            print(f"\n✓ Testing with admin: {admin.get_full_name()}")
            
            clients = get_filtered_clients(admin)
            loans = get_filtered_loans(admin)
            applications = get_filtered_applications(admin)
            repayments = get_filtered_repayments(admin)
            
            print(f"  - Clients: {clients.count()}")
            print(f"  - Loans: {loans.count()}")
            print(f"  - Applications: {applications.count()}")
            print(f"  - Repayments: {repayments.count()}")
        else:
            print("⚠ No admin user found for testing")
        
        # Test with loan officer
        loan_officer = CustomUser.objects.filter(
            role='loan_officer', 
            is_active=True
        ).first()
        
        if loan_officer:
            print(f"\n✓ Testing with loan officer: {loan_officer.get_full_name()}")
            
            clients = get_filtered_clients(loan_officer)
            loans = get_filtered_loans(loan_officer)
            
            print(f"  - Clients (portfolio): {clients.count()}")
            print(f"  - Loans (portfolio): {loans.count()}")
            
            # Verify portfolio filtering is working
            if clients.count() > 0:
                # Check that all clients have this loan officer as portfolio manager
                non_portfolio = clients.exclude(portfolio_manager=loan_officer).count()
                if non_portfolio == 0:
                    print(f"  ✓ Portfolio filtering working correctly")
                else:
                    print(f"  ✗ Portfolio filtering issue: {non_portfolio} clients not in portfolio")
        else:
            print("⚠ No loan officer found for testing")
        
        # Test with secretary
        secretary = CustomUser.objects.filter(
            role='secretary',
            is_active=True
        ).first()
        
        if secretary:
            print(f"\n✓ Testing with secretary: {secretary.get_full_name()}")
            
            if hasattr(secretary, 'branch') and secretary.branch:
                clients = get_filtered_clients(secretary)
                loans = get_filtered_loans(secretary)
                
                print(f"  - Branch: {secretary.branch.name}")
                print(f"  - Clients (branch): {clients.count()}")
                print(f"  - Loans (branch): {loans.count()}")
                
                # Verify branch filtering is working
                if clients.count() > 0:
                    non_branch = clients.exclude(branch=secretary.branch).count()
                    if non_branch == 0:
                        print(f"  ✓ Branch filtering working correctly")
                    else:
                        print(f"  ✗ Branch filtering issue: {non_branch} clients not in branch")
            else:
                print("  ⚠ Secretary has no branch assigned")
        else:
            print("⚠ No secretary found for testing")
        
        return True
        
    except Exception as e:
        print(f"\n✗ Error testing filtering functions: {e}")
        import traceback
        traceback.print_exc()
        return False


def verify_user_context():
    """Verify user context function"""
    print("\n" + "="*60)
    print("VERIFYING USER CONTEXT")
    print("="*60)
    
    try:
        users = CustomUser.objects.filter(is_active=True)[:3]
        
        for user in users:
            context = get_user_context(user)
            print(f"\n✓ {user.get_full_name()} ({user.role})")
            print(f"  - Is Admin: {context['is_admin']}")
            print(f"  - Is Portfolio Manager: {context['is_portfolio_manager']}")
            print(f"  - Is Branch Staff: {context['is_branch_staff']}")
            print(f"  - Branch: {context['branch_name'] or 'None'}")
        
        return True
        
    except Exception as e:
        print(f"\n✗ Error testing user context: {e}")
        return False


def verify_branch_filtering():
    """Verify branch filtering works correctly"""
    print("\n" + "="*60)
    print("VERIFYING BRANCH FILTERING")
    print("="*60)
    
    try:
        admin = CustomUser.objects.filter(role='admin', is_active=True).first()
        if not admin:
            print("⚠ No admin user found for testing")
            return False
        
        branches = Branch.objects.all()
        
        for branch in branches:
            print(f"\n✓ Testing branch: {branch.name}")
            
            clients = get_filtered_clients(admin, branch.id)
            loans = get_filtered_loans(admin, branch.id)
            
            print(f"  - Clients: {clients.count()}")
            print(f"  - Loans: {loans.count()}")
            
            # Verify all clients are from this branch
            if clients.count() > 0:
                non_branch = clients.exclude(branch=branch).count()
                if non_branch == 0:
                    print(f"  ✓ All clients from {branch.name}")
                else:
                    print(f"  ✗ {non_branch} clients from other branches")
        
        return True
        
    except Exception as e:
        print(f"\n✗ Error testing branch filtering: {e}")
        return False


def main():
    print("\n" + "="*60)
    print("COMPREHENSIVE FILTERING VERIFICATION")
    print("="*60)
    
    results = {
        'imports': verify_imports(),
        'functions': verify_filtering_functions(),
        'context': verify_user_context(),
        'branch_filtering': verify_branch_filtering(),
    }
    
    print("\n" + "="*60)
    print("VERIFICATION RESULTS")
    print("="*60)
    
    all_passed = True
    for test_name, result in results.items():
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{status} - {test_name.replace('_', ' ').title()}")
        if not result:
            all_passed = False
    
    print("\n" + "="*60)
    if all_passed:
        print("✓ ALL VERIFICATIONS PASSED")
        print("="*60)
        print("\nFiltering implementation is complete and working correctly!")
        print("\nNext steps:")
        print("1. Test the dashboard with different user roles")
        print("2. Verify all reports show correct filtered data")
        print("3. Check that branch selector works properly")
        print("4. Ensure staff can only see their authorized data")
    else:
        print("✗ SOME VERIFICATIONS FAILED")
        print("="*60)
        print("\nPlease review the errors above and fix any issues.")
    
    print()


if __name__ == '__main__':
    main()
