#!/usr/bin/env python
"""
Quick fix for production database - Add missing nickname column
Run this on your production server to fix the OperationalError
"""

import os
import sys
import django

# 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 fix_database():
    """Add missing nickname column to users table"""
    print("Fixing production database...")
    
    try:
        from django.db import connection
        
        with connection.cursor() as cursor:
            # Check if nickname column exists
            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 already exists")
                return True
            
            # Add the nickname column
            print("Adding nickname column to users table...")
            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: {e}")
        return False

def run_migrations():
    """Run Django migrations"""
    print("Running Django migrations...")
    try:
        from django.core.management import execute_from_command_line
        execute_from_command_line(['manage.py', 'migrate'])
        print("✓ Migrations completed successfully!")
        return True
    except Exception as e:
        print(f"Migration error: {e}")
        return False

if __name__ == '__main__':
    print("Production Database Fix Script")
    print("=" * 40)
    
    # First try to add the column directly
    if fix_database():
        print("\nDatabase fix completed!")
    else:
        print("\nTrying Django migrations instead...")
        if run_migrations():
            print("Migrations completed successfully!")
        else:
            print("Failed to fix database. Please check your database connection and permissions.")
    
    print("\nScript completed!") 