#!/usr/bin/env python3
"""
Fix for the missing users_user_permissions table that's causing the 
"Field 'permission_id' doesn't have a default value" error in production.

This script creates the missing Django-generated table for the user_permissions
ManyToManyField in the CustomUser model.
"""

import os
import sys
import django
import logging
from django.db import connection, transaction

# Setup Django
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_table_exists(table_name):
    """Check if a table exists in the database"""
    with connection.cursor() as cursor:
        cursor.execute("SHOW TABLES LIKE %s", [table_name])
        return cursor.fetchone() is not None

def get_id_column_type():
    """Get the appropriate ID column type based on the users table"""
    with connection.cursor() as cursor:
        cursor.execute("DESCRIBE users")
        columns = cursor.fetchall()
        for col in columns:
            if col[0] == 'id':
                return col[1]
    return 'CHAR(32)'  # Default fallback

def create_users_user_permissions_table():
    """Create the missing users_user_permissions table"""
    logger.info("Creating users_user_permissions table...")
    
    if check_table_exists('users_user_permissions'):
        logger.info("users_user_permissions table already exists")
        return True
    
    try:
        with connection.cursor() as cursor:
            # Get the correct ID column type from the users table
            id_column_type = get_id_column_type()
            logger.info(f"Using ID column type: {id_column_type}")
            
            # Create the users_user_permissions table
            create_sql = f"""
            CREATE TABLE users_user_permissions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                customuser_id {id_column_type} NOT NULL,
                permission_id INT NOT NULL,
                UNIQUE KEY users_user_permissions_customuser_id_permission_id_uniq (customuser_id, permission_id),
                KEY users_user_permissions_customuser_id (customuser_id),
                KEY users_user_permissions_permission_id (permission_id),
                CONSTRAINT users_user_permissions_customuser_id_fk 
                    FOREIGN KEY (customuser_id) REFERENCES users (id) ON DELETE CASCADE,
                CONSTRAINT users_user_permissions_permission_id_fk 
                    FOREIGN KEY (permission_id) REFERENCES auth_permission (id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """
            
            cursor.execute(create_sql)
            logger.info("✅ Successfully created users_user_permissions table")
            
            # Verify the table was created correctly
            cursor.execute("DESCRIBE users_user_permissions")
            columns = cursor.fetchall()
            logger.info("Table structure:")
            for col in columns:
                logger.info(f"  {col[0]}: {col[1]} {col[2]} {col[3]} {col[4]} {col[5]}")
            
            return True
            
    except Exception as e:
        logger.error(f"❌ Error creating users_user_permissions table: {e}")
        return False

def create_users_groups_table():
    """Create the users_groups table if it doesn't exist"""
    logger.info("Checking users_groups table...")
    
    if check_table_exists('users_groups'):
        logger.info("users_groups table already exists")
        return True
    
    try:
        with connection.cursor() as cursor:
            id_column_type = get_id_column_type()
            
            create_sql = f"""
            CREATE TABLE users_groups (
                id INT AUTO_INCREMENT PRIMARY KEY,
                customuser_id {id_column_type} NOT NULL,
                group_id INT NOT NULL,
                UNIQUE KEY users_groups_customuser_id_group_id_uniq (customuser_id, group_id),
                KEY users_groups_customuser_id (customuser_id),
                KEY users_groups_group_id (group_id),
                CONSTRAINT users_groups_customuser_id_fk 
                    FOREIGN KEY (customuser_id) REFERENCES users (id) ON DELETE CASCADE,
                CONSTRAINT users_groups_group_id_fk 
                    FOREIGN KEY (group_id) REFERENCES auth_group (id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """
            
            cursor.execute(create_sql)
            logger.info("✅ Successfully created users_groups table")
            return True
            
    except Exception as e:
        logger.error(f"❌ Error creating users_groups table: {e}")
        return False

def verify_django_tables():
    """Verify that all required Django tables exist"""
    required_tables = [
        'users_user_permissions',
        'users_groups'
    ]
    
    missing_tables = []
    for table in required_tables:
        if not check_table_exists(table):
            missing_tables.append(table)
    
    if missing_tables:
        logger.error(f"❌ Missing tables: {missing_tables}")
        return False
    else:
        logger.info("✅ All required Django tables exist")
        return True

def main():
    """Main function to fix the permission issue"""
    logger.info("=" * 60)
    logger.info("FIXING USERS_USER_PERMISSIONS TABLE ISSUE")
    logger.info("=" * 60)
    
    try:
        # Create the missing tables
        success1 = create_users_user_permissions_table()
        success2 = create_users_groups_table()
        
        if success1 and success2:
            # Verify everything is working
            if verify_django_tables():
                logger.info("🎉 SUCCESS: All Django user permission tables are now properly configured!")
                logger.info("The 'Field permission_id doesn't have a default value' error should be resolved.")
                return True
            else:
                logger.error("❌ Verification failed")
                return False
        else:
            logger.error("❌ Failed to create required tables")
            return False
            
    except Exception as e:
        logger.error(f"❌ Unexpected error: {e}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
