#!/usr/bin/env python3
"""
Fix the custom user_permissions table that's causing the permission error.
This is different from Django's built-in users_user_permissions table.
"""

import os
import sys
import django
import logging
from django.db import connection, transaction

# Setup Django for production
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def check_custom_user_permissions_table():
    """Check the structure of the custom user_permissions table"""
    logger.info("Checking custom user_permissions table structure...")
    
    with connection.cursor() as cursor:
        cursor.execute("DESCRIBE user_permissions")
        columns = cursor.fetchall()
        
        logger.info("Current user_permissions table structure:")
        for col in columns:
            logger.info(f"  {col[0]}: {col[1]} {col[2]} {col[3]} {col[4]} {col[5]}")
        
        # Check if permission_id has a default value
        permission_id_col = None
        for col in columns:
            if col[0] == 'permission_id':
                permission_id_col = col
                break
        
        if permission_id_col:
            logger.info(f"permission_id column: {permission_id_col[1]} {permission_id_col[2]} {permission_id_col[3]} {permission_id_col[4]} {permission_id_col[5]}")
            
            if permission_id_col[2] == 'NO' and permission_id_col[4] is None:
                logger.warning("❌ PROBLEM: permission_id is NOT NULL with no default value")
                return False
            else:
                logger.info("✅ permission_id column looks correct")
                return True
        else:
            logger.error("❌ permission_id column not found")
            return False

def fix_custom_user_permissions_table():
    """Fix the custom user_permissions table"""
    logger.info("Fixing custom user_permissions table...")
    
    try:
        with connection.cursor() as cursor:
            # Check current structure
            cursor.execute("DESCRIBE user_permissions")
            columns = cursor.fetchall()
            
            # Find the permission_id column
            permission_id_col = None
            for col in columns:
                if col[0] == 'permission_id':
                    permission_id_col = col
                    break
            
            if not permission_id_col:
                logger.error("permission_id column not found in user_permissions table")
                return False
            
            # Check if it needs fixing
            if permission_id_col[2] == 'NO' and permission_id_col[4] is None:
                logger.info("permission_id column needs fixing - adding default value")
                
                # Add a default value to the permission_id column
                # We'll set it to 0 as a default (you might want to change this)
                cursor.execute("ALTER TABLE user_permissions MODIFY COLUMN permission_id INT NOT NULL DEFAULT 0")
                logger.info("✅ Added default value to permission_id column")
                
                # Verify the change
                cursor.execute("DESCRIBE user_permissions")
                columns = cursor.fetchall()
                for col in columns:
                    if col[0] == 'permission_id':
                        logger.info(f"Updated permission_id column: {col[1]} {col[2]} {col[3]} {col[4]} {col[5]}")
                        break
                
                return True
            else:
                logger.info("permission_id column already has a default value")
                return True
                
    except Exception as e:
        logger.error(f"❌ Error fixing user_permissions table: {e}")
        return False

def test_custom_user_permissions():
    """Test the custom user_permissions table"""
    logger.info("Testing custom user_permissions table...")
    
    try:
        from users.models import UserPermission
        from users.models import CustomUser
        
        # Test creating a UserPermission record
        user = CustomUser.objects.first()
        if not user:
            logger.error("No user found for testing")
            return False
        
        # Test creating a UserPermission
        try:
            permission = UserPermission.objects.create(
                user=user,
                module='test',
                action='view',
                is_allowed=True
            )
            logger.info("✅ Successfully created UserPermission record")
            
            # Clean up
            permission.delete()
            logger.info("✅ Successfully deleted test record")
            
            return True
            
        except Exception as e:
            logger.error(f"❌ Error creating UserPermission: {e}")
            return False
        
    except Exception as e:
        logger.error(f"❌ Error testing user_permissions: {e}")
        return False

def main():
    """Main function to fix the custom user_permissions table"""
    logger.info("=" * 60)
    logger.info("FIXING CUSTOM USER_PERMISSIONS TABLE")
    logger.info("=" * 60)
    
    try:
        # Check current structure
        if not check_custom_user_permissions_table():
            logger.info("Table needs fixing...")
            
            # Fix the table
            if fix_custom_user_permissions_table():
                logger.info("✅ Table fixed successfully")
            else:
                logger.error("❌ Failed to fix table")
                return False
        else:
            logger.info("Table structure looks correct")
        
        # Test the table
        if test_custom_user_permissions():
            logger.info("✅ Custom user_permissions table is working correctly")
        else:
            logger.error("❌ Custom user_permissions table test failed")
            return False
        
        logger.info("🎉 SUCCESS: Custom user_permissions table is now working correctly!")
        logger.info("The 'Field permission_id doesn't have a default value' error should be resolved.")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        return False

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