#!/usr/bin/env python
"""
Non-interactive script to apply pending migrations to production database
This script automatically applies migrations without requiring user input
"""

import os
import sys
import django
from django.core.management import execute_from_command_line

# Add the project directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')

# Setup Django
django.setup()

def apply_migrations():
    """Apply pending migrations to the database"""
    print("Starting migration process...")
    
    # Check for pending migrations
    print("Checking for pending migrations...")
    try:
        execute_from_command_line(['manage.py', 'showmigrations'])
    except Exception as e:
        print(f"Error checking migrations: {e}")
    
    # Apply migrations
    print("\nApplying migrations...")
    try:
        execute_from_command_line(['manage.py', 'migrate'])
        print("✓ Migrations applied successfully!")
        return True
    except Exception as e:
        print(f"Migration error: {e}")
        return False

def check_database():
    """Check database connection and status"""
    print("Checking database connection...")
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            print("Database connection successful!")
            
            # Check if users table exists and has nickname column
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users' 
                AND COLUMN_NAME = 'nickname'
            """)
            result = cursor.fetchone()
            if result:
                print("✓ nickname column exists in users table")
                return True
            else:
                print("✗ nickname column missing from users table")
                return False
                
    except Exception as e:
        print(f"Database connection failed: {e}")
        return False

def add_nickname_column():
    """Directly add the nickname column to the database"""
    print("Adding nickname column directly...")
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("""
                ALTER TABLE users 
                ADD COLUMN nickname VARCHAR(100) NULL
            """)
            print("✓ nickname column added successfully!")
            return True
    except Exception as e:
        print(f"Error adding column: {e}")
        return False

if __name__ == '__main__':
    print("Production Migration Script (Non-Interactive)")
    print("=" * 50)
    
    # Check database first
    if check_database():
        print("\n✓ Database is ready - nickname column exists")
    else:
        print("\n✗ Database needs fixing - nickname column missing")
        
        # Try to add the column directly first
        if add_nickname_column():
            print("✓ Database fixed successfully!")
        else:
            print("Trying Django migrations...")
            if apply_migrations():
                print("✓ Migrations completed successfully!")
            else:
                print("✗ Failed to fix database")
                sys.exit(1)
    
    print("\nScript completed successfully!") 