"""
Verify migration state is consistent after cleanup.
"""
import os
import sys
import django
from pathlib import Path

# Add the project root directory to Python path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.recorder import MigrationRecorder

def check_migration_consistency():
    """Check that migration state is consistent."""
    print("Checking migration consistency...")
    
    # Get migration state from disk and database
    loader = MigrationLoader(connection)
    recorder = MigrationRecorder(connection)
    applied = recorder.applied_migrations()
    
    # Check each app's migrations
    apps = ['utils', 'loans', 'users', 'reports']
    has_errors = False
    
    for app in apps:
        print(f"\nChecking {app} migrations...")
        
        # Get disk migrations
        disk_migrations = set()
        for name, migration in loader.disk_migrations.items():
            if name[0] == app:
                disk_migrations.add(name)
                
        # Get applied migrations for this app
        app_applied = set()
        for name in applied:
            if name[0] == app:
                app_applied.add(name)
                
        # Check for inconsistencies
        not_applied = disk_migrations - app_applied
        if not_applied:
            print(f"ERROR: Found migrations on disk that are not applied:")
            for migration in sorted(not_applied):
                print(f" - {migration[0]}.{migration[1]}")
            has_errors = True
            
        applied_not_on_disk = app_applied - disk_migrations
        if applied_not_on_disk:
            print(f"ERROR: Found applied migrations that are not on disk:")
            for migration in sorted(applied_not_on_disk):
                print(f" - {migration[0]}.{migration[1]}")
            has_errors = True
            
        # Verify dependencies
        for name, migration in loader.disk_migrations.items():
            if name[0] != app:
                continue
                
            for dep_app, dep_name in migration.dependencies:
                dep_tuple = (dep_app, dep_name)
                if dep_tuple not in applied and dep_tuple in loader.disk_migrations:
                    print(f"ERROR: Migration {name[0]}.{name[1]} depends on "
                          f"{dep_app}.{dep_name} but dependency is not applied")
                    has_errors = True
                    
    if not has_errors:
        print("\nAll migrations appear to be consistent!")
        return True
    else:
        print("\nFound migration inconsistencies!")
        return False

if __name__ == '__main__':
    success = check_migration_consistency()
    sys.exit(0 if success else 1)
