#!/usr/bin/env python
"""
Script to run migrations on production database
"""
import os
import sys
import django

# Set up Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

from django.core.management import call_command
from django.db import connection

def check_column_exists(table_name, column_name):
    """Check if a column exists in a table"""
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = %s 
            AND COLUMN_NAME = %s
        """, [table_name, column_name])
        return cursor.fetchone()[0] > 0

def main():
    print("=" * 60)
    print("Production Database Migration Script")
    print("=" * 60)
    
    # Check current state
    print("\nChecking current database state...")
    
    tables_to_check = {
        'loan_products': ['penalty_mode', 'penalty_frequency'],
        'penalty_charges': ['applied_by_id', 'is_automatic', 'reason']
    }
    
    missing_columns = []
    for table, columns in tables_to_check.items():
        for column in columns:
            exists = check_column_exists(table, column)
            status = "✓ EXISTS" if exists else "✗ MISSING"
            print(f"  {table}.{column}: {status}")
            if not exists:
                missing_columns.append(f"{table}.{column}")
    
    if missing_columns:
        print(f"\n⚠ Found {len(missing_columns)} missing columns")
        print("\nRunning migrations...")
        
        try:
            # Run migrations
            call_command('migrate', '--noinput', verbosity=2)
            print("\n✓ Migrations completed successfully!")
            
        except Exception as e:
            print(f"\n✗ Error running migrations: {e}")
            print("\nYou may need to run the SQL script manually:")
            print("  mysql -u username -p database_name < add_penalty_columns_production.sql")
            sys.exit(1)
    else:
        print("\n✓ All required columns exist!")
        print("Running migrations to ensure everything is up to date...")
        try:
            call_command('migrate', '--noinput', verbosity=1)
            print("✓ Database is up to date!")
        except Exception as e:
            print(f"⚠ Warning: {e}")
    
    print("\n" + "=" * 60)
    print("Migration check complete!")
    print("=" * 60)

if __name__ == '__main__':
    main()
