#!/usr/bin/env python
"""
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

print("Fixing django_content_type table...")
print("=" * 60)

with connection.cursor() as cursor:
    # Check current structure
    cursor.execute("DESCRIBE django_content_type")
    print("\nCurrent structure:")
    for col in cursor.fetchall():
        print(f"  {col}")
    
    # Check for existing data
    cursor.execute("SELECT COUNT(*) FROM django_content_type")
    count = cursor.fetchone()[0]
    print(f"\nExisting records: {count}")
    
    if count > 0:
        # Backup data
        cursor.execute("SELECT * FROM django_content_type")
        backup_data = cursor.fetchall()
        print(f"✓ Backed up {len(backup_data)} records")
    
    # Drop and recreate table
    print("\nRecreating table with correct structure...")
    cursor.execute("DROP TABLE IF EXISTS django_content_type")
    cursor.execute("""
        CREATE TABLE django_content_type (
            id INT AUTO_INCREMENT PRIMARY KEY,
            app_label VARCHAR(100) NOT NULL,
            model VARCHAR(100) NOT NULL,
            UNIQUE KEY django_content_type_app_label_model_76bd3d3b_uniq (app_label, model)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    """)
    print("✓ Table recreated")
    
    if count > 0:
        # Restore data
        print("\nRestoring data...")
        for row in backup_data:
            cursor.execute(
                "INSERT INTO django_content_type (id, app_label, model) VALUES (%s, %s, %s)",
                row
            )
        print(f"✓ Restored {len(backup_data)} records")

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