"""
Create missing tables directly using Django's schema editor
"""
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.db import connection
from django.apps import apps
from django.db.backends.base.schema import BaseDatabaseSchemaEditor

print("="*60)
print("  CREATE MISSING TABLES DIRECTLY")
print("="*60)

def table_exists(table_name):
    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 create_model_table(model):
    """Create table for a model"""
    table_name = model._meta.db_table
    
    if table_exists(table_name):
        print(f"  ✅ {table_name} already exists")
        return True
    
    print(f"  Creating {table_name}...")
    try:
        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(model)
        print(f"  ✅ {table_name} created")
        return True
    except Exception as e:
        print(f"  ❌ Error creating {table_name}: {e}")
        return False

print("\nStep 1: Get models that need tables...")
print("-"*60)

# Get the models
try:
    CustomUser = apps.get_model('users', 'CustomUser')
    print("✅ Found CustomUser model")
except Exception as e:
    print(f"❌ CustomUser model not found: {e}")
    CustomUser = None

try:
    Loan = apps.get_model('loans', 'Loan')
    print("✅ Found Loan model")
except Exception as e:
    print(f"❌ Loan model not found: {e}")
    Loan = None

try:
    Client = apps.get_model('loans', 'Client')
    print("✅ Found Client model")
except Exception as e:
    print(f"❌ Client model not found: {e}")
    Client = None

try:
    Repayment = apps.get_model('loans', 'Repayment')
    print("✅ Found Repayment model")
except Exception as e:
    print(f"❌ Repayment model not found: {e}")
    Repayment = None

print("\n" + "="*60)
print("Step 2: Create missing tables...")
print("="*60)

models_to_create = []
if CustomUser:
    models_to_create.append(('users_customuser', CustomUser))
if Client:
    models_to_create.append(('loans_client', Client))
if Loan:
    models_to_create.append(('loans_loan', Loan))
if Repayment:
    models_to_create.append(('loans_repayment', Repayment))

success_count = 0
for table_name, model in models_to_create:
    if create_model_table(model):
        success_count += 1

print("\n" + "="*60)
print("Step 3: Verify all critical tables...")
print("="*60)

critical_tables = [
    'users_customuser',
    'users_branch',
    'loans_loan',
    'loans_client',
    'loans_loanapplication',
    'loans_repayment',
]

all_exist = True
for table in critical_tables:
    if table_exists(table):
        print(f"✅ {table}")
    else:
        print(f"❌ {table} - STILL MISSING")
        all_exist = False

if all_exist:
    print("\n" + "="*60)
    print("  ✅ SUCCESS! All tables created")
    print("="*60)
    print("\nYour 500 error is now fixed!")
    print("\nFinal steps:")
    print("1. Set DEBUG=False in production")
    print("2. Restart your application")
    print("3. Test the site")
else:
    print("\n" + "="*60)
    print("  ⚠️  Some tables still missing")
    print("="*60)
    print("\nTrying alternative approach...")
    print("Run this SQL directly in your database:")
    print("\nSHOW CREATE TABLE users_customuser;")
    print("\nOr check if models exist in your code:")
    print("  users/models.py - CustomUser")
    print("  loans/models.py - Loan, Client, Repayment")
