"""
Emergency fix for production - Reset and reapply migrations
RUN THIS ON PRODUCTION SERVER ONLY
"""
import os
import sys

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import django
django.setup()

from django.core.management import call_command
from django.db import connection

print("="*60)
print("  EMERGENCY PRODUCTION FIX")
print("="*60)

print("\nWARNING: This will reset migration state!")
print("Press Ctrl+C to cancel, or wait 3 seconds...")

import time
time.sleep(3)

print("\nStep 1: Reset migration state for users and loans...")
print("-"*60)

try:
    print("Resetting users migrations...")
    call_command('migrate', 'users', 'zero', '--fake', verbosity=2)
    print("✅ users reset")
except Exception as e:
    print(f"⚠️  Error: {e}")

try:
    print("\nResetting loans migrations...")
    call_command('migrate', 'loans', 'zero', '--fake', verbosity=2)
    print("✅ loans reset")
except Exception as e:
    print(f"⚠️  Error: {e}")

print("\n" + "="*60)
print("Step 2: Reapply all migrations...")
print("="*60)

try:
    print("Applying users migrations...")
    call_command('migrate', 'users', verbosity=2)
    print("✅ users migrated")
except Exception as e:
    print(f"❌ Error: {e}")

try:
    print("\nApplying loans migrations...")
    call_command('migrate', 'loans', verbosity=2)
    print("✅ loans migrated")
except Exception as e:
    print(f"❌ Error: {e}")

try:
    print("\nApplying all remaining migrations...")
    call_command('migrate', '--run-syncdb', verbosity=2)
    print("✅ All migrations applied")
except Exception as e:
    print(f"❌ Error: {e}")

print("\n" + "="*60)
print("Step 3: Verify tables...")
print("="*60)

with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    tables = [table[0] for table in cursor.fetchall()]
    
    critical = [
        'users_customuser',
        'users_branch',
        'loans_loan',
        'loans_loanapplication',
        'loans_repayment',
    ]
    
    all_exist = True
    for table in critical:
        if table in tables:
            print(f"✅ {table}")
        else:
            print(f"❌ {table} - MISSING")
            all_exist = False

if all_exist:
    print("\n" + "="*60)
    print("  ✅ SUCCESS!")
    print("="*60)
    print("\nAll tables created. Now:")
    print("1. Set DEBUG=False")
    print("2. Restart application")
    print("3. Test the site")
else:
    print("\n" + "="*60)
    print("  ⚠️  TABLES STILL MISSING")
    print("="*60)
    print("\nContact support or check:")
    print("1. Are models defined in code?")
    print("2. Are apps in INSTALLED_APPS?")
    print("3. Check ~/logs/error_log for details")
