#!/usr/bin/env python
"""
Fix django_migrations 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_migrations table...")
print("=" * 60)

with connection.cursor() as cursor:
    # Check if table exists
    cursor.execute("SHOW TABLES LIKE 'django_migrations'")
    table_exists = cursor.fetchone()
    
    if table_exists:
        print("✓ django_migrations table exists")
        
        # Check current structure
        cursor.execute("DESCRIBE django_migrations")
        columns = cursor.fetchall()
        print("\nCurrent structure:")
        for col in columns:
            print(f"  {col[0]}: {col[1]}")
        
        # Drop and recreate with correct structure
        print("\nRecreating table with correct structure...")
        cursor.execute("DROP TABLE IF EXISTS django_migrations")
        cursor.execute("""
            CREATE TABLE django_migrations (
                id INT AUTO_INCREMENT PRIMARY KEY,
                app VARCHAR(255) NOT NULL,
                name VARCHAR(255) NOT NULL,
                applied DATETIME(6) NOT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("✓ Table recreated successfully")
    else:
        print("Creating django_migrations table...")
        cursor.execute("""
            CREATE TABLE django_migrations (
                id INT AUTO_INCREMENT PRIMARY KEY,
                app VARCHAR(255) NOT NULL,
                name VARCHAR(255) NOT NULL,
                applied DATETIME(6) NOT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("✓ Table created successfully")

print("\n" + "=" * 60)
print("django_migrations table fixed!")
print("\nNow run: python sync_migration_history.py")
