#!/usr/bin/env python3
"""
Simple verification script to check if branch filtering fixes are applied correctly
"""

import os
import sys

def check_file_content(file_path, search_patterns):
    """Check if file contains the expected patterns"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        results = {}
        for pattern_name, pattern in search_patterns.items():
            results[pattern_name] = pattern in content
            
        return results, content
    except FileNotFoundError:
        return None, None

def main():
    print("🔍 Verifying Branch Filtering Fixes")
    print("=" * 40)
    
    # Check utils/views.py for branch filtering fixes
    utils_views_path = "utils/views.py"
    
    patterns_to_check = {
        "receipts_branch_filtering": "selected_branch_id = request.session.get('selected_branch_id')",
        "receipts_superuser_check": "if request.user.is_superuser and not selected_branch_id:",
        "receipts_branch_filter": "borrower__branch_id=selected_branch_id",
        "notifications_branch_filtering": "Q(user__branch_id=selected_branch_id) | Q(user__isnull=True)",
        "documents_branch_filtering": "Q(uploaded_by__branch_id=selected_branch_id) |",
        "documents_shared_filter": "Q(shared_with=user) |",
        "documents_public_filter": "Q(is_public=True)"
    }
    
    results, content = check_file_content(utils_views_path, patterns_to_check)
    
    if results is None:
        print(f"❌ Could not find {utils_views_path}")
        return
    
    print(f"📁 Checking {utils_views_path}")
    print("-" * 30)
    
    all_good = True
    for pattern_name, found in results.items():
        status = "✅" if found else "❌"
        print(f"{status} {pattern_name}: {'Found' if found else 'Missing'}")
        if not found:
            all_good = False
    
    print()
    
    # Check specific function implementations
    functions_to_check = [
        ("receipts_list", "def receipts_list(request):"),
        ("notifications", "def notifications(request):"),
        ("documents", "def documents(request):")
    ]
    
    print("🔧 Function Implementation Check")
    print("-" * 30)
    
    for func_name, func_signature in functions_to_check:
        if func_signature in content:
            print(f"✅ {func_name}: Function found")
            
            # Extract function content (rough approximation)
            start_idx = content.find(func_signature)
            if start_idx != -1:
                # Find the next function or end of file
                next_func_idx = content.find("\n@", start_idx + 1)
                if next_func_idx == -1:
                    next_func_idx = content.find("\ndef ", start_idx + len(func_signature))
                
                if next_func_idx != -1:
                    func_content = content[start_idx:next_func_idx]
                else:
                    func_content = content[start_idx:start_idx + 2000]  # Take first 2000 chars
                
                # Check for branch filtering in this function
                has_branch_filtering = "selected_branch_id" in func_content
                branch_status = "✅" if has_branch_filtering else "❌"
                print(f"  {branch_status} Branch filtering: {'Implemented' if has_branch_filtering else 'Missing'}")
        else:
            print(f"❌ {func_name}: Function not found")
            all_good = False
    
    print()
    
    if all_good:
        print("🎉 All branch filtering fixes appear to be implemented correctly!")
        print("\n📋 Summary of fixes:")
        print("• Receipts page now filters by selected branch")
        print("• Notifications page filters by branch + system notifications")
        print("• Documents page filters by branch + shared + public documents")
        print("• Superusers can see all data when no branch is selected")
        print("• Staff users have appropriate access levels")
    else:
        print("⚠️ Some fixes may be missing or incomplete.")
        print("Please review the implementation.")
    
    print("\n🔗 Pages that should now work with branch filtering:")
    print("• /utils/receipts/")
    print("• /utils/notifications/")
    print("• /utils/documents/")

if __name__ == '__main__':
    main()