"""
Fix django_content_type table structure
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection

def fix_content_type_table():
    """Fix django_content_type table"""
    with connection.cursor() as cursor:
        # Check current structure
        print("Checking django_content_type table structure...")
        cursor.execute("DESCRIBE django_content_type")
        columns = {row[0] for row in cursor.fetchall()}
        print(f"Current columns: {columns}")
        
        # Drop and recreate the table with correct structure
        print("\nRecreating django_content_type table...")
        
        # Disable foreign key checks
        cursor.execute("SET FOREIGN_KEY_CHECKS=0")
        print("✓ Disabled foreign key checks")
        
        cursor.execute("DROP TABLE IF EXISTS django_content_type")
        print("✓ Dropped old table")
        
        cursor.execute("""
            CREATE TABLE `django_content_type` (
              `id` int NOT NULL AUTO_INCREMENT,
              `app_label` varchar(100) NOT NULL,
              `model` varchar(100) NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `django_content_type_app_label_model_76bd3d3b_uniq` (`app_label`,`model`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("✓ Created new table with correct structure")
        
        # Re-enable foreign key checks
        cursor.execute("SET FOREIGN_KEY_CHECKS=1")
        print("✓ Re-enabled foreign key checks")
        
        # Verify
        cursor.execute("DESCRIBE django_content_type")
        new_columns = [row[0] for row in cursor.fetchall()]
        print(f"\nNew columns: {new_columns}")
        
        print("\n✅ django_content_type table fixed!")
        print("\nNext steps:")
        print("1. Run: python manage.py migrate contenttypes")
        print("2. Run: python manage.py migrate --run-syncdb")
        print("3. Run: python manage.py migrate --fake")

if __name__ == '__main__':
    try:
        fix_content_type_table()
    except Exception as e:
        print(f"\n❌ Error: {str(e)}")
        import traceback
        traceback.print_exc()
