"""
Fix Production 500 Error - Missing Tables Issue
"""
import os
import sys
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

django.setup()

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

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

def main():
    print("="*60)
    print("  FIXING PRODUCTION 500 ERROR")
    print("="*60)
    
    # Check critical tables
    critical_tables = {
        'users_customuser': 'users',
        'loans_loan': 'loans',
        'loans_client': 'loans',
    }
    
    missing_tables = []
    print("\n1. Checking tables...")
    for table, app in critical_tables.items():
        exists = check_table_exists(table)
        if exists:
            print(f"  ✅ {table}")
        else:
            print(f"  ❌ {table} - MISSING")
            missing_tables.append((table, app))
    
    if missing_tables:
        print(f"\n2. Found {len(missing_tables)} missing tables")
        print("\nAttempting to create tables...")
        
        # Get unique apps
        apps_to_migrate = list(set([app for _, app in missing_tables]))
        
        for app in apps_to_migrate:
            print(f"\n  Migrating {app}...")
            try:
                call_command('migrate', app, '--fake-initial', verbosity=2)
                print(f"  ✅ {app} migrated")
            except Exception as e:
                print(f"  ⚠️  Error with --fake-initial: {e}")
                print(f"  Trying without --fake-initial...")
                try:
                    call_command('migrate', app, verbosity=2)
                    print(f"  ✅ {app} migrated")
                except Exception as e2:
                    print(f"  ❌ Failed: {e2}")
        
        # Verify tables now exist
        print("\n3. Verifying tables...")
        all_exist = True
        for table, app in missing_tables:
            exists = check_table_exists(table)
            if exists:
                print(f"  ✅ {table} - NOW EXISTS")
            else:
                print(f"  ❌ {table} - STILL MISSING")
                all_exist = False
        
        if all_exist:
            print("\n✅ SUCCESS! All tables created")
        else:
            print("\n⚠️  Some tables still missing")
            print("\nManual fix needed:")
            print("  python manage.py migrate --run-syncdb")
    else:
        print("\n✅ All critical tables exist")
    
    print("\n" + "="*60)
    print("  ADDITIONAL FIXES NEEDED")
    print("="*60)
    
    print("\n1. Update ALLOWED_HOSTS in settings:")
    print("   Add your domain: 'branchbusinessadvance.co.ke'")
    print("   Add www version: 'www.branchbusinessadvance.co.ke'")
    
    print("\n2. Set DEBUG = False in production")
    
    print("\n3. Restart your application:")
    print("   - cPanel: Touch restart file or restart app")
    print("   - Apache: sudo systemctl restart apache2")
    
    print("\n4. Check web server error logs for specific errors")
    print("   cPanel: ~/logs/error_log")

if __name__ == '__main__':
    main()
