#!/usr/bin/env python3
"""
Skip Problematic Migrations

This script skips problematic migrations and focuses on getting the
user_permissions table working correctly.

Usage:
    python skip_problematic_migrations.py
"""

import os
import sys
import django
import subprocess
from pathlib import Path

def setup_django():
    """Setup Django environment"""
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        django.setup()
        print("[SUCCESS] Django environment setup successful")
        return True
    except Exception as e:
        print(f"[ERROR] Django setup failed: {str(e)}")
        return False

def check_user_permissions_table():
    """Check if user_permissions table is working"""
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM user_permissions WHERE module = 'test'")
            result = cursor.fetchone()
            print("[SUCCESS] user_permissions table is working correctly")
            return True
    except Exception as e:
        print(f"[ERROR] user_permissions table not working: {str(e)}")
        return False

def skip_problematic_migrations():
    """Skip problematic migrations and focus on user_permissions"""
    print("=" * 60)
    print("SKIPPING PROBLEMATIC MIGRATIONS")
    print("=" * 60)
    
    if not setup_django():
        return False
    
    # Step 1: Check if user_permissions table is already working
    print("Step 1: Checking if user_permissions table is working...")
    if check_user_permissions_table():
        print("[SUCCESS] user_permissions table is already working!")
        return True
    
    # Step 2: Mark problematic migrations as fake
    print("Step 2: Marking problematic migrations as fake...")
    
    problematic_migrations = [
        '0018_add_unassigned_date_field',
        '0019_remove_rolepermission_role_permis_role_056d99_idx_and_more',
        '0019_alter_customuser_role',
        '0020_remove_rolepermission_role_permis_role_056d99_idx_and_more',
        '0021_update_module_field_length',
        '0022_remove_rolepermission_role_permis_role_056d99_idx_and_more',
        '0023_merge_20251014_1744'
    ]
    
    for migration in problematic_migrations:
        print(f"Marking {migration} as fake...")
        try:
            result = subprocess.run([
                'python', 'manage.py', 'migrate', 'users', migration, '--fake'
            ], capture_output=True, text=True, cwd=Path.cwd())
            
            if result.returncode == 0:
                print(f"[SUCCESS] {migration} marked as fake")
            else:
                print(f"[WARNING] Could not mark {migration} as fake: {result.stderr}")
        except Exception as e:
            print(f"[WARNING] Error marking {migration} as fake: {str(e)}")
    
    # Step 3: Check migration status
    print("Step 3: Checking migration status...")
    try:
        result = subprocess.run([
            'python', 'manage.py', 'showmigrations', 'users'
        ], capture_output=True, text=True, cwd=Path.cwd())
        
        if result.returncode == 0:
            print("Migration status after marking as fake:")
            print(result.stdout)
        else:
            print(f"Error checking migration status: {result.stderr}")
    except Exception as e:
        print(f"Error checking migration status: {str(e)}")
    
    # Step 4: Verify user_permissions table
    print("Step 4: Verifying user_permissions table...")
    if check_user_permissions_table():
        print("[SUCCESS] user_permissions table is working after skipping problematic migrations!")
        return True
    else:
        print("[ERROR] user_permissions table is still not working")
        return False

def main():
    """Main function"""
    try:
        success = skip_problematic_migrations()
        
        if success:
            print("=" * 60)
            print("PROBLEMATIC MIGRATIONS SKIPPED SUCCESSFULLY!")
            print("The user_permissions table should now work correctly.")
            print("=" * 60)
        else:
            print("=" * 60)
            print("FAILED TO SKIP PROBLEMATIC MIGRATIONS")
            print("Please check the error messages above.")
            print("=" * 60)
        
        return success
        
    except Exception as e:
        print(f"Script failed: {str(e)}")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
