#!/usr/bin/env python
"""
Script to apply pending migrations to production database
This script should be run on the production server
"""

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...")
    execute_from_command_line(['manage.py', 'showmigrations'])
    
    # Apply migrations
    print("\nApplying migrations...")
    execute_from_command_line(['manage.py', 'migrate'])
    
    # Verify migrations
    print("\nVerifying migrations...")
    execute_from_command_line(['manage.py', 'showmigrations'])
    
    print("\nMigration process completed!")

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")
            else:
                print("✗ nickname column missing from users table")
                
    except Exception as e:
        print(f"Database connection failed: {e}")
        return False
    
    return True

if __name__ == '__main__':
    print("Production Migration Script")
    print("=" * 40)
    
    # Check database first
    if check_database():
        # Ask for confirmation
        response = input("\nDo you want to apply pending migrations? (y/N): ")
        if response.lower() in ['y', 'yes']:
            apply_migrations()
        else:
            print("Migration cancelled.")
    else:
        print("Cannot proceed due to database connection issues.") 