#!/usr/bin/env python3
"""
Migration Conflict Fix Script

This script fixes the Django migration conflicts that are preventing the
user_permissions table from being properly set up.

Usage:
    python fix_migration_conflicts.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_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(command, description):
    """Run a command and log the result"""
    logger.info(f"Running: {description}")
    logger.info(f"Command: {' '.join(command)}")
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        
        if result.returncode == 0:
            logger.info(f"[SUCCESS] {description}")
            if result.stdout:
                logger.info(f"Output: {result.stdout}")
            return True
        else:
            logger.error(f"[FAILED] {description}")
            if result.stderr:
                logger.error(f"Error: {result.stderr}")
            if result.stdout:
                logger.info(f"Output: {result.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"""
    logger.info("=" * 60)
    logger.info("FIXING DJANGO MIGRATION CONFLICTS")
    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...")
    if not run_command(['python', 'manage.py', 'showmigrations', 'users'], "Check migration status"):
        logger.warning("Could not check migration status, continuing...")
    
    # Step 2: Merge conflicting migrations
    logger.info("Step 2: Merging conflicting migrations...")
    if not run_command(['python', 'manage.py', 'makemigrations', '--merge', 'users'], "Merge conflicting migrations"):
        logger.error("Failed to merge migrations")
        return False
    
    # Step 3: Create any missing migrations
    logger.info("Step 3: Creating missing migrations...")
    if not run_command(['python', 'manage.py', 'makemigrations', 'users'], "Create missing migrations"):
        logger.warning("No new migrations needed or failed to create migrations")
    
    # Step 4: Apply migrations
    logger.info("Step 4: Applying migrations...")
    if not run_command(['python', 'manage.py', 'migrate', 'users'], "Apply migrations"):
        logger.error("Failed to apply migrations")
        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)
