#!/usr/bin/env python3
"""
Database Fix Verification Script

This script verifies that the user_permissions database fix is working correctly
and that the permission-based navigation system is ready to use.

Usage:
    python verify_database_fix.py
"""

import os
import sys
import django

def setup_django():
    """Setup Django environment"""
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        django.setup()
        print("[SUCCESS] Django environment setup successful")
        return True
    except Exception as e:
        print(f"[ERROR] Django setup failed: {str(e)}")
        return False

def verify_user_permissions_table():
    """Verify the user_permissions table is working"""
    print("\n" + "="*60)
    print("VERIFYING USER_PERMISSIONS TABLE")
    print("="*60)
    
    try:
        from django.db import connection
        
        with connection.cursor() as cursor:
            # Check if table exists
            cursor.execute("SHOW TABLES LIKE 'user_permissions'")
            table_exists = cursor.fetchone()
            
            if not table_exists:
                print("[ERROR] user_permissions table does not exist")
                return False
            
            print("[SUCCESS] user_permissions table exists")
            
            # Check table structure
            cursor.execute("DESCRIBE user_permissions")
            columns = cursor.fetchall()
            
            required_columns = ['id', 'user_id', 'module', 'action', 'is_allowed', 'granted_by_id', 'reason', 'expires_at', 'created_at', 'updated_at']
            column_names = [col[0] for col in columns]
            
            missing_columns = []
            for col in required_columns:
                if col not in column_names:
                    missing_columns.append(col)
            
            if missing_columns:
                print(f"[ERROR] Missing columns: {missing_columns}")
                return False
            
            print("[SUCCESS] All required columns exist")
            
            # Check module column type
            for col in columns:
                if col[0] == 'module':
                    if 'varchar(50)' in col[1].lower():
                        print("[SUCCESS] Module column has correct type (VARCHAR(50))")
                    else:
                        print(f"[WARNING] Module column type: {col[1]} (should be VARCHAR(50))")
                    break
            
            # Test query
            cursor.execute("SELECT COUNT(*) FROM user_permissions WHERE module = 'test'")
            result = cursor.fetchone()
            print("[SUCCESS] Can query user_permissions table successfully")
            
            return True
            
    except Exception as e:
        print(f"[ERROR] Error verifying user_permissions table: {str(e)}")
        return False

def verify_django_models():
    """Verify Django models are working"""
    print("\n" + "="*60)
    print("VERIFYING DJANGO MODELS")
    print("="*60)
    
    try:
        from users.models import UserPermission, CustomUser
        
        # Test model import
        print("[SUCCESS] UserPermission model imported successfully")
        print("[SUCCESS] CustomUser model imported successfully")
        
        # Test model methods
        if hasattr(CustomUser, 'has_permission'):
            print("[SUCCESS] CustomUser.has_permission method exists")
        else:
            print("[ERROR] CustomUser.has_permission method missing")
            return False
        
        # Test creating a permission (without saving)
        try:
            user = CustomUser.objects.first()
            if user:
                # Test the has_permission method
                has_access = user.has_permission('dashboard', 'access')
                print(f"[SUCCESS] has_permission method works (result: {has_access})")
            else:
                print("[WARNING] No users found to test has_permission method")
        except Exception as e:
            print(f"[ERROR] Error testing has_permission method: {str(e)}")
            return False
        
        return True
        
    except Exception as e:
        print(f"[ERROR] Error verifying Django models: {str(e)}")
        return False

def verify_template_filters():
    """Verify template filters are working"""
    print("\n" + "="*60)
    print("VERIFYING TEMPLATE FILTERS")
    print("="*60)
    
    try:
        from users.templatetags.permission_filters import has_module_access
        
        print("[SUCCESS] has_module_access template filter imported successfully")
        
        # Test the filter function
        from users.models import CustomUser
        user = CustomUser.objects.first()
        
        if user:
            result = has_module_access(user, 'dashboard')
            print(f"[SUCCESS] has_module_access filter works (result: {result})")
        else:
            print("[WARNING] No users found to test template filter")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] Error verifying template filters: {str(e)}")
        return False

def verify_navigation_system():
    """Verify navigation system components"""
    print("\n" + "="*60)
    print("VERIFYING NAVIGATION SYSTEM")
    print("="*60)
    
    try:
        # Check if base template exists and has permission checks
        base_template_path = "templates/base.html"
        if os.path.exists(base_template_path):
            with open(base_template_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            if 'has_module_access' in content:
                print("[SUCCESS] Base template contains permission checks")
            else:
                print("[WARNING] Base template may not have permission checks")
            
            if 'permission_filters' in content:
                print("[SUCCESS] Base template loads permission_filters")
            else:
                print("[WARNING] Base template may not load permission_filters")
        else:
            print("[ERROR] Base template not found")
            return False
        
        return True
        
    except Exception as e:
        print(f"[ERROR] Error verifying navigation system: {str(e)}")
        return False

def main():
    """Main verification function"""
    print("="*80)
    print("DATABASE FIX VERIFICATION")
    print("="*80)
    print("This script verifies that the user_permissions database fix is working")
    print("and that the permission-based navigation system is ready to use.")
    
    # Setup Django
    if not setup_django():
        return False
    
    # Run all verifications
    verifications = [
        verify_user_permissions_table,
        verify_django_models,
        verify_template_filters,
        verify_navigation_system
    ]
    
    all_passed = True
    for verification in verifications:
        if not verification():
            all_passed = False
    
    # Summary
    print("\n" + "="*80)
    if all_passed:
        print("VERIFICATION COMPLETED SUCCESSFULLY!")
        print("="*80)
        print("[SUCCESS] The user_permissions table is working correctly")
        print("[SUCCESS] Django models are functioning properly")
        print("[SUCCESS] Template filters are working")
        print("[SUCCESS] Navigation system is ready")
        print("\n[COMPLETE] The permission-based navigation system is ready to use!")
        print("\nNext steps:")
        print("1. Go to Staff Management -> Select a user -> User Permissions")
        print("2. Try checking/unchecking the 'Access' permission for any module")
        print("3. Save the permissions")
        print("4. Log in as that user and verify navigation items show/hide correctly")
    else:
        print("VERIFICATION FAILED")
        print("="*80)
        print("[ERROR] Some components are not working correctly")
        print("Please check the error messages above and fix any issues.")
    
    return all_passed

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
