#!/usr/bin/env python
"""
Sync migration history by directly updating django_migrations table
"""
import os
import django

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

from django.db import connection
from django.db.migrations.recorder import MigrationRecorder

print("Syncing migration history...")
print("=" * 60)

# Check if django_migrations table exists
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES LIKE 'django_migrations'")
    if not cursor.fetchone():
        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
            )
        """)
        print("✓ django_migrations table created")

# Get all migration files
from django.db.migrations.loader import MigrationLoader
loader = MigrationLoader(connection)

print(f"\nFound {len(loader.disk_migrations)} migrations on disk")

# Get applied migrations
recorder = MigrationRecorder(connection)
applied = set(recorder.applied_migrations())
print(f"Found {len(applied)} migrations in database")

# Find unapplied migrations
unapplied = []
for key in loader.disk_migrations.keys():
    if key not in applied:
        unapplied.append(key)

print(f"\nFound {len(unapplied)} unapplied migrations")

if unapplied:
    print("\nMarking migrations as applied (fake)...")
    for app_label, migration_name in sorted(unapplied):
        try:
            recorder.record_applied(app_label, migration_name)
            print(f"  ✓ {app_label}.{migration_name}")
        except Exception as e:
            print(f"  ⚠ {app_label}.{migration_name}: {e}")

print("\n" + "=" * 60)
print("Migration history synced!")
print("\nYou can now run: python manage.py runserver")
