#!/usr/bin/env python3
"""
Deployment script for Utils Branch Filtering Fixes

This script ensures that the branch filtering fixes for utils pages are properly deployed:
- /utils/receipts/
- /utils/notifications/  
- /utils/documents/

The fixes ensure that users only see data relevant to their selected branch.
"""

import os
import sys
import django
from django.conf import settings

# Add the project root to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

def check_branch_filtering_implementation():
    """Check if branch filtering is properly implemented"""
    
    print("🔍 Checking Utils Branch Filtering Implementation")
    print("=" * 50)
    
    # Check if utils/views.py exists and has the required functions
    utils_views_path = "utils/views.py"
    
    if not os.path.exists(utils_views_path):
        print(f"❌ {utils_views_path} not found!")
        return False
    
    with open(utils_views_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Check for required implementations
    checks = [
        ("receipts_list function", "def receipts_list(request):"),
        ("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 function", "def notifications(request):"),
        ("notifications branch filtering", "Q(user__branch_id=selected_branch_id) | Q(user__isnull=True)"),
        ("documents function", "def documents(request):"),
        ("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)"),
        ("all_customer_documents branch filtering", "clients.filter(branch_id=selected_branch_id)")
    ]
    
    all_passed = True
    for check_name, pattern in checks:
        if pattern in content:
            print(f"✅ {check_name}: Found")
        else:
            print(f"❌ {check_name}: Missing")
            all_passed = False
    
    return all_passed

def test_database_connectivity():
    """Test database connectivity"""
    
    print("\n🔗 Testing Database Connectivity")
    print("-" * 30)
    
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            if result[0] == 1:
                print("✅ Database connection successful")
                return True
            else:
                print("❌ Database connection failed")
                return False
    except Exception as e:
        print(f"❌ Database error: {e}")
        return False

def check_models():
    """Check if required models exist"""
    
    print("\n📊 Checking Required Models")
    print("-" * 30)
    
    try:
        from utils.models import Receipt, Notification, Document
        from users.models import CustomUser, Branch
        
        print("✅ Receipt model: Available")
        print("✅ Notification model: Available")
        print("✅ Document model: Available")
        print("✅ CustomUser model: Available")
        print("✅ Branch model: Available")
        
        # Check if models have required fields
        receipt_fields = [f.name for f in Receipt._meta.fields]
        if 'borrower' in receipt_fields:
            print("✅ Receipt.borrower field: Available")
        else:
            print("❌ Receipt.borrower field: Missing")
            return False
            
        notification_fields = [f.name for f in Notification._meta.fields]
        if 'user' in notification_fields:
            print("✅ Notification.user field: Available")
        else:
            print("❌ Notification.user field: Missing")
            return False
            
        document_fields = [f.name for f in Document._meta.fields]
        if 'uploaded_by' in document_fields:
            print("✅ Document.uploaded_by field: Available")
        else:
            print("❌ Document.uploaded_by field: Missing")
            return False
            
        user_fields = [f.name for f in CustomUser._meta.fields]
        if 'branch' in user_fields:
            print("✅ CustomUser.branch field: Available")
        else:
            print("❌ CustomUser.branch field: Missing")
            return False
        
        return True
        
    except ImportError as e:
        print(f"❌ Model import error: {e}")
        return False
    except Exception as e:
        print(f"❌ Model check error: {e}")
        return False

def check_urls():
    """Check if URL patterns are configured"""
    
    print("\n🔗 Checking URL Configuration")
    print("-" * 30)
    
    try:
        from django.urls import reverse
        
        # Test URL patterns
        urls_to_check = [
            ('utils:receipts_list', '/utils/receipts/'),
            ('utils:notifications', '/utils/notifications/'),
            ('utils:documents', '/utils/documents/'),
            ('utils:all_customer_documents', '/utils/documents/all-customers/')
        ]
        
        for url_name, expected_path in urls_to_check:
            try:
                url = reverse(url_name)
                print(f"✅ {url_name}: {url}")
            except Exception as e:
                print(f"❌ {url_name}: Error - {e}")
                return False
        
        return True
        
    except Exception as e:
        print(f"❌ URL check error: {e}")
        return False

def run_deployment_checks():
    """Run all deployment checks"""
    
    print("🚀 Utils Branch Filtering Deployment Checks")
    print("=" * 60)
    
    checks = [
        ("Implementation Check", check_branch_filtering_implementation),
        ("Database Connectivity", test_database_connectivity),
        ("Models Check", check_models),
        ("URLs Check", check_urls)
    ]
    
    all_passed = True
    results = {}
    
    for check_name, check_func in checks:
        try:
            result = check_func()
            results[check_name] = result
            if not result:
                all_passed = False
        except Exception as e:
            print(f"❌ {check_name} failed with error: {e}")
            results[check_name] = False
            all_passed = False
    
    print("\n📋 Deployment Summary")
    print("=" * 30)
    
    for check_name, result in results.items():
        status = "✅ PASSED" if result else "❌ FAILED"
        print(f"{status} {check_name}")
    
    if all_passed:
        print("\n🎉 All checks passed! Branch filtering is ready for production.")
        print("\n📝 What was fixed:")
        print("• Receipts page (/utils/receipts/) now filters by selected branch")
        print("• Notifications page (/utils/notifications/) filters by branch + system alerts")
        print("• Documents page (/utils/documents/) filters by branch + shared + public docs")
        print("• All customer documents page filters by selected branch")
        print("• Superusers can see all data when no branch is selected")
        print("• Staff users have appropriate access based on their branch")
        
        print("\n🔧 How it works:")
        print("• Uses session-stored 'selected_branch_id' for filtering")
        print("• Superusers without branch selection see all data")
        print("• Users with branches see only their branch data")
        print("• System notifications are visible to all users")
        print("• Public documents are visible to all users")
        print("• Shared documents are visible to recipients")
        
        return True
    else:
        print("\n⚠️ Some checks failed. Please review the issues above.")
        return False

if __name__ == '__main__':
    success = run_deployment_checks()
    sys.exit(0 if success else 1)