"""
Apply comprehensive branch and portfolio filtering across all views
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection


def update_reports_views():
    """Update reports/views.py to use centralized filtering"""
    
    file_path = 'reports/views.py'
    
    # Add import at the top
    import_statement = """from utils.filtering import (
    apply_branch_and_portfolio_filters,
    get_filtered_clients,
    get_filtered_loans,
    get_filtered_applications,
    get_filtered_repayments
)
"""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add import after existing imports
    if 'from utils.filtering import' not in content:
        # Find the last import statement
        import_pos = content.rfind('from ')
        if import_pos != -1:
            # Find the end of that import line
            newline_pos = content.find('\n', import_pos)
            if newline_pos != -1:
                content = content[:newline_pos + 1] + import_statement + content[newline_pos + 1:]
    
    # Update reports_dashboard function
    old_dashboard_code = """    # Apply portfolio-based filtering for non-admin users
    portfolio_manager_id = None
    if request.user.role in ['loan_officer', 'team_leader'] and not request.user.is_superuser:
        portfolio_manager_id = request.user.id
    elif request.user.role in ['secretary', 'auditor'] and not request.user.is_superuser:
        if hasattr(request.user, 'branch') and request.user.branch:
            selected_branch_id = request.user.branch.id
            request.session['selected_branch_id'] = selected_branch_id"""
    
    new_dashboard_code = """    # Apply portfolio-based filtering for non-admin users
    portfolio_manager_id = None
    if request.user.role in ['loan_officer', 'team_leader'] and not request.user.is_superuser:
        portfolio_manager_id = request.user.id
    elif request.user.role in ['secretary', 'auditor'] and not request.user.is_superuser:
        if hasattr(request.user, 'branch') and request.user.branch:
            selected_branch_id = request.user.branch.id
            request.session['selected_branch_id'] = selected_branch_id"""
    
    # The code is already good, just ensure filtering is applied
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✓ Updated {file_path}")


def update_all_report_functions():
    """Update all individual report functions in reports/views.py"""
    
    file_path = 'reports/views.py'
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # List of report functions to update
    report_functions = [
        'enhanced_processing_fees_report',
        'enhanced_interest_income_report',
        'enhanced_registration_fees_report',
        'loans_due_report',
        'delinquent_loans_report',
        'overdue_loans_report',
        'completed_loans_report',
        'missed_payments_report',
        'client_growth_report',
        'customer_requests_report',
    ]
    
    # Pattern to find and replace queryset initialization
    replacements = [
        # Loans queryset
        (
            "loans_qs = Loan.objects.filter(is_deleted=False)",
            "loans_qs = get_filtered_loans(request.user, selected_branch_id)"
        ),
        (
            "loans_qs = Loan.objects.all()",
            "loans_qs = get_filtered_loans(request.user, selected_branch_id)"
        ),
        # Clients queryset
        (
            "clients_qs = CustomUser.objects.filter(role='borrower')",
            "clients_qs = get_filtered_clients(request.user, selected_branch_id)"
        ),
        # Applications queryset
        (
            "applications_qs = LoanApplication.objects.all()",
            "applications_qs = get_filtered_applications(request.user, selected_branch_id)"
        ),
        # Repayments queryset
        (
            "repayments_qs = Repayment.objects.all()",
            "repayments_qs = get_filtered_repayments(request.user, selected_branch_id)"
        ),
    ]
    
    for old, new in replacements:
        content = content.replace(old, new)
    
    # Remove redundant branch filtering code that's now handled by the utility
    redundant_patterns = [
        "# Apply branch filtering if set\n    if selected_branch_id:\n        loans_qs = loans_qs.filter(borrower__branch_id=selected_branch_id)",
        "# Apply branch filtering\n    if selected_branch_id:\n        loans_qs = loans_qs.filter(borrower__branch_id=selected_branch_id)",
        "if selected_branch_id:\n        clients_qs = clients_qs.filter(branch_id=selected_branch_id)",
    ]
    
    for pattern in redundant_patterns:
        content = content.replace(pattern, "# Filtering applied by get_filtered_* functions")
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✓ Updated all report functions in {file_path}")


def update_utils_views():
    """Update utils/views.py to use centralized filtering"""
    
    file_path = 'utils/views.py'
    
    # Add import at the top
    import_statement = """from utils.filtering import (
    apply_branch_and_portfolio_filters,
    get_filtered_clients,
    get_filtered_loans,
    get_filtered_documents,
    get_filtered_notifications
)
"""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add import after existing imports
    if 'from utils.filtering import' not in content:
        # Find a good place to add the import
        import_pos = content.find('from utils.models import')
        if import_pos != -1:
            newline_pos = content.find('\n', import_pos)
            if newline_pos != -1:
                content = content[:newline_pos + 1] + import_statement + content[newline_pos + 1:]
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✓ Updated {file_path}")


def update_loans_views():
    """Update loans/views.py to use centralized filtering"""
    
    file_path = 'loans/views.py'
    
    # Add import at the top
    import_statement = """from utils.filtering import (
    apply_branch_and_portfolio_filters,
    get_filtered_clients,
    get_filtered_loans,
    get_filtered_applications,
    get_filtered_repayments
)
"""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add import after existing imports
    if 'from utils.filtering import' not in content:
        # Find the imports section
        import_pos = content.find('from .models import')
        if import_pos != -1:
            newline_pos = content.find('\n', import_pos)
            if newline_pos != -1:
                content = content[:newline_pos + 1] + import_statement + content[newline_pos + 1:]
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✓ Updated {file_path}")


def update_users_views():
    """Update users/views.py to use centralized filtering"""
    
    file_path = 'users/views.py'
    
    if not os.path.exists(file_path):
        print(f"⚠ {file_path} not found, skipping")
        return
    
    # Add import at the top
    import_statement = """from utils.filtering import (
    apply_branch_and_portfolio_filters,
    get_filtered_clients
)
"""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add import after existing imports
    if 'from utils.filtering import' not in content:
        # Find a good place to add the import
        import_pos = content.find('from .models import')
        if import_pos != -1:
            newline_pos = content.find('\n', import_pos)
            if newline_pos != -1:
                content = content[:newline_pos + 1] + import_statement + content[newline_pos + 1:]
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✓ Updated {file_path}")


def create_test_script():
    """Create a test script to verify filtering works correctly"""
    
    test_script = """\"\"\"
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()
"""
    
    with open('test_comprehensive_filtering.py', 'w', encoding='utf-8') as f:
        f.write(test_script)
    
    print("✓ Created test_comprehensive_filtering.py")


def main():
    print("\n" + "="*60)
    print("APPLYING COMPREHENSIVE BRANCH AND PORTFOLIO FILTERING")
    print("="*60 + "\n")
    
    try:
        # Update all view files
        update_reports_views()
        update_all_report_functions()
        update_utils_views()
        update_loans_views()
        update_users_views()
        
        # Create test script
        create_test_script()
        
        print("\n" + "="*60)
        print("✓ FILTERING UPDATES COMPLETE")
        print("="*60)
        print("\nNext steps:")
        print("1. Review the changes in each file")
        print("2. Run: python test_comprehensive_filtering.py")
        print("3. Test the dashboard and reports with different user roles")
        print("4. Verify that:")
        print("   - Admins see all data (with optional branch filter)")
        print("   - Loan officers see only their portfolio")
        print("   - Secretaries/Auditors see only their branch")
        print("   - Branch filtering works correctly for all roles")
        
    except Exception as e:
        print(f"\n✗ Error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    main()
