"""
Simple script to create the missing utils_auditlog table
"""
import os
import django

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

from django.db import connection

def create_table():
    """Create the utils_auditlog table"""
    create_sql = """
    CREATE TABLE IF NOT EXISTS `utils_auditlog` (
        `id` char(32) NOT NULL,
        `action` varchar(50) NOT NULL,
        `model_name` varchar(100) NOT NULL,
        `object_id` varchar(50) NOT NULL,
        `description` longtext NOT NULL,
        `ip_address` char(39) DEFAULT NULL,
        `user_agent` varchar(255) DEFAULT NULL,
        `created_at` datetime(6) NOT NULL,
        `user_id` char(32) DEFAULT NULL,
        PRIMARY KEY (`id`),
        KEY `utils_auditlog_user_id_idx` (`user_id`),
        KEY `utils_auditlog_created_at_idx` (`created_at`),
        CONSTRAINT `utils_auditlog_user_id_fk` 
            FOREIGN KEY (`user_id`) 
            REFERENCES `users_customuser` (`id`) 
            ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    """
    
    try:
        with connection.cursor() as cursor:
            print("Creating utils_auditlog table...")
            cursor.execute(create_sql)
            print("✓ Table created successfully!")
            
            # Verify it exists
            cursor.execute("""
                SELECT COUNT(*)
                FROM information_schema.tables 
                WHERE table_schema = DATABASE()
                AND table_name = 'utils_auditlog'
            """)
            result = cursor.fetchone()
            
            if result[0] > 0:
                print("✓ Verified: Table 'utils_auditlog' exists in database")
            else:
                print("✗ Warning: Table creation may have failed")
                
    except Exception as e:
        print(f"✗ Error: {e}")
        return False
    
    return True

if __name__ == '__main__':
    create_table()
