"""
Force create all missing tables - Production Fix
"""
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("  FORCE CREATE MISSING TABLES")
print("="*60)

print("\nStep 1: Check current state...")
call_command('showmigrations')

print("\n" + "="*60)
print("Step 2: Create any missing migrations...")
print("="*60)
call_command('makemigrations')

print("\n" + "="*60)
print("Step 3: Apply migrations with --run-syncdb...")
print("="*60)
call_command('migrate', '--run-syncdb')

print("\n" + "="*60)
print("Step 4: Verify tables exist...")
print("="*60)

with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    tables = [table[0] for table in cursor.fetchall()]
    
    critical = ['users_customuser', 'loans_loan', 'loans_client']
    
    for table in critical:
        if table in tables:
            print(f"✅ {table}")
        else:
            print(f"❌ {table} - MISSING")

print("\n" + "="*60)
print("DONE! Check results above.")
print("="*60)
print("\nIf tables still missing, the issue may be:")
print("1. Model not in INSTALLED_APPS")
print("2. Migration files corrupted")
print("3. Database permissions issue")
