#!/usr/bin/env python
"""
Fix all Django core tables that are missing AUTO_INCREMENT
"""
import os
import django

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

from django.db import connection

print("Fixing all Django core tables...")
print("=" * 60)

# List of Django core tables that need fixing
django_tables = [
    'django_content_type',
    'auth_permission',
    'auth_group',
    'auth_group_permissions',
    'django_admin_log',
    'django_session',
]

with connection.cursor() as cursor:
    # Get all tables
    cursor.execute("SHOW TABLES")
    all_tables = [table[0] for table in cursor.fetchall()]
    
    for table in all_tables:
        try:
            # Get table structure
            cursor.execute(f"DESCRIBE `{table}`")
            columns = cursor.fetchall()
            
            # Find id column
            has_id = False
            needs_fix = False
            
            for col in columns:
                if col[0] == 'id':
                    has_id = True
                    col_name, col_type, col_null, col_key, col_default, col_extra = col
                    
                    # Check if it needs AUTO_INCREMENT
                    if 'auto_increment' not in col_extra.lower():
                        needs_fix = True
                        
                        print(f"\nFixing {table}...")
                        print(f"  Current: {col_type} {col_extra or '(no extra)'}")
                        
                        # Determine the correct type
                        if 'bigint' in col_type.lower():
                            new_type = 'BIGINT'
                        else:
                            new_type = 'INT'
                        
                        # Check if it's a primary key
                        if col_key == 'PRI':
                            # Modify column to add AUTO_INCREMENT
                            cursor.execute(f"""
                                ALTER TABLE `{table}` 
                                MODIFY COLUMN `id` {new_type} NOT NULL AUTO_INCREMENT
                            """)
                        else:
                            # Add primary key and AUTO_INCREMENT
                            cursor.execute(f"""
                                ALTER TABLE `{table}` 
                                ADD PRIMARY KEY (`id`),
                                MODIFY COLUMN `id` {new_type} NOT NULL AUTO_INCREMENT
                            """)
                        
                        print(f"  ✓ Fixed: {new_type} AUTO_INCREMENT")
                    break
                    
        except Exception as e:
            print(f"  ⚠ Error on {table}: {e}")

print("\n" + "=" * 60)
print("All Django tables fixed!")
print("\nNow run: python manage.py migrate")
