#!/usr/bin/env python3
"""
Check what migrations are recorded in the database
"""

import os
import sys
import django
from django.db import connection

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

def check_migrations():
    """Check what migrations are in the database"""
    print("🔍 Checking migrations in database...")
    
    try:
        with connection.cursor() as cursor:
            # Check if django_migrations table exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.tables 
                WHERE table_schema = DATABASE() 
                AND table_name = 'django_migrations'
            """)
            
            if cursor.fetchone()[0] == 0:
                print("❌ django_migrations table doesn't exist")
                return
            
            # Get all migrations
            cursor.execute("""
                SELECT app, name, applied 
                FROM django_migrations 
                ORDER BY app, name
            """)
            
            migrations = cursor.fetchall()
            
            print(f"📊 Found {len(migrations)} migrations:")
            
            current_app = None
            for app, name, applied in migrations:
                if app != current_app:
                    print(f"\n📱 {app}:")
                    current_app = app
                print(f"  ✅ {name} ({applied})")
            
            # Check for the problematic migration
            cursor.execute("""
                SELECT COUNT(*) 
                FROM django_migrations 
                WHERE app = 'utils' AND name = '0015_notification_related_loan'
            """)
            
            count = cursor.fetchone()[0]
            if count > 0:
                print(f"\n⚠️  Found problematic migration in database: utils.0015_notification_related_loan")
                
                # Delete it
                cursor.execute("""
                    DELETE FROM django_migrations 
                    WHERE app = 'utils' AND name = '0015_notification_related_loan'
                """)
                print("✅ Removed problematic migration from database")
            
            # Check for missing loans migration
            cursor.execute("""
                SELECT COUNT(*) 
                FROM django_migrations 
                WHERE app = 'loans' AND name = '0014_merge_20250827_0154'
            """)
            
            count = cursor.fetchone()[0]
            if count == 0:
                print(f"\n⚠️  Missing loans migration: 0014_merge_20250827_0154")
                
                # Add it as fake
                cursor.execute("""
                    INSERT INTO django_migrations (app, name, applied) 
                    VALUES ('loans', '0014_merge_20250827_0154', NOW())
                """)
                print("✅ Added fake migration to database")
                
    except Exception as e:
        print(f"❌ ERROR: {e}")

if __name__ == "__main__":
    check_migrations()
