#!/usr/bin/env python
"""
Fix AUTO_INCREMENT on all tables that need it
"""
import os
import django

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

from django.db import connection

print("Fixing AUTO_INCREMENT on all tables...")
print("=" * 60)

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

print("\n" + "=" * 60)
print(f"Fixed {fixed_count} tables")
print("\nNow run: python manage.py migrate")
