#!/usr/bin/env python3
"""
Automatic Migration Fix Script

This script automatically handles Django migration conflicts by providing
the necessary input to the merge command.

Usage:
    python fix_migrations_auto.py
"""

import os
import sys
import subprocess
import logging
from pathlib import Path

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('migration_auto_fix.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

def setup_django():
    """Setup Django environment"""
    try:
        import django
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        django.setup()
        logger.info("Django environment setup successful")
        return True
    except Exception as e:
        logger.error(f"Django setup failed: {str(e)}")
        return False

def run_command_with_input(command, input_text, description):
    """Run a command with automatic input"""
    logger.info(f"Running: {description}")
    logger.info(f"Command: {' '.join(command)}")
    
    try:
        process = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            cwd=Path.cwd()
        )
        
        stdout, stderr = process.communicate(input=input_text)
        
        if process.returncode == 0:
            logger.info(f"[SUCCESS] {description}")
            if stdout:
                logger.info(f"Output: {stdout}")
            return True
        else:
            logger.error(f"[FAILED] {description}")
            if stderr:
                logger.error(f"Error: {stderr}")
            if stdout:
                logger.info(f"Output: {stdout}")
            return False
            
    except Exception as e:
        logger.error(f"Error running command: {str(e)}")
        return False

def fix_migration_conflicts():
    """Fix Django migration conflicts automatically"""
    logger.info("=" * 60)
    logger.info("AUTOMATIC MIGRATION CONFLICT FIX")
    logger.info("=" * 60)
    
    # Setup Django
    if not setup_django():
        return False
    
    # Step 1: Check current migration status
    logger.info("Step 1: Checking current migration status...")
    try:
        result = subprocess.run(
            ['python', 'manage.py', 'showmigrations', 'users'],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        if result.returncode == 0:
            logger.info("Migration status checked successfully")
            logger.info(f"Output: {result.stdout}")
        else:
            logger.warning("Could not check migration status, continuing...")
    except Exception as e:
        logger.warning(f"Error checking migration status: {str(e)}")
    
    # Step 2: Merge conflicting migrations with automatic 'yes' input
    logger.info("Step 2: Merging conflicting migrations automatically...")
    if not run_command_with_input(
        ['python', 'manage.py', 'makemigrations', '--merge', 'users'],
        'y\n',  # Automatically answer 'yes' to merge
        "Merge conflicting migrations"
    ):
        logger.warning("Migration merge failed or no conflicts to merge")
    
    # Step 3: Create any missing migrations
    logger.info("Step 3: Creating missing migrations...")
    try:
        result = subprocess.run(
            ['python', 'manage.py', 'makemigrations', 'users'],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        if result.returncode == 0:
            logger.info("Migration creation completed")
            if result.stdout:
                logger.info(f"Output: {result.stdout}")
        else:
            logger.warning("No new migrations needed or failed to create migrations")
    except Exception as e:
        logger.warning(f"Error creating migrations: {str(e)}")
    
    # Step 4: Apply migrations
    logger.info("Step 4: Applying migrations...")
    try:
        result = subprocess.run(
            ['python', 'manage.py', 'migrate', 'users'],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        if result.returncode == 0:
            logger.info("Migrations applied successfully")
            if result.stdout:
                logger.info(f"Output: {result.stdout}")
        else:
            logger.error(f"Failed to apply migrations: {result.stderr}")
            return False
    except Exception as e:
        logger.error(f"Error applying migrations: {str(e)}")
        return False
    
    # Step 5: Verify the fix
    logger.info("Step 5: Verifying the fix...")
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM user_permissions WHERE module = 'test'")
            result = cursor.fetchone()
            logger.info("[SUCCESS] user_permissions table is working correctly")
            return True
    except Exception as e:
        logger.error(f"[FAILED] Verification failed: {str(e)}")
        return False

def main():
    """Main function"""
    try:
        success = fix_migration_conflicts()
        
        if success:
            logger.info("=" * 60)
            logger.info("MIGRATION CONFLICTS FIXED SUCCESSFULLY!")
            logger.info("The user_permissions table should now work correctly.")
            logger.info("=" * 60)
        else:
            logger.error("=" * 60)
            logger.error("FAILED TO FIX MIGRATION CONFLICTS")
            logger.error("Please check the error messages above.")
            logger.error("=" * 60)
        
        return success
        
    except Exception as e:
        logger.error(f"Script failed: {str(e)}")
        return False

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