"""
Create missing tables by making and applying migrations
"""
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.core.management import call_command
from django.db import connection

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("  CREATING MISSING TABLES")
    print("="*60)
    
    print("\n1. Making migrations for users and utils apps...")
    try:
        call_command('makemigrations', 'users', verbosity=2)
        print("  ✅ users migrations created")
    except Exception as e:
        print(f"  ⚠️  users: {e}")
    
    try:
        call_command('makemigrations', 'utils', verbosity=2)
        print("  ✅ utils migrations created")
    except Exception as e:
        print(f"  ⚠️  utils: {e}")
    
    print("\n2. Running migrate with --run-syncdb...")
    try:
        call_command('migrate', '--run-syncdb', verbosity=2)
        print("  ✅ Migrations applied with syncdb")
    except Exception as e:
        print(f"  ❌ Error: {e}")
        print("\n  Trying regular migrate...")
        try:
            call_command('migrate', verbosity=2)
            print("  ✅ Regular migrate completed")
        except Exception as e2:
            print(f"  ❌ Failed: {e2}")
    
    print("\n3. Verifying critical tables...")
    critical_tables = [
        'users_customuser',
        'loans_loan',
        'loans_client',
        'loans_loanapplication',
        'loans_repayment',
    ]
    
    all_exist = True
    for table in critical_tables:
        exists = check_table_exists(table)
        if exists:
            print(f"  ✅ {table}")
        else:
            print(f"  ❌ {table} - MISSING")
            all_exist = False
    
    if all_exist:
        print("\n" + "="*60)
        print("  ✅ SUCCESS! All tables created")
        print("="*60)
        print("\nNext steps:")
        print("1. Set DEBUG=False in production (.env file)")
        print("2. Restart your application")
        print("3. Test the site")
    else:
        print("\n" + "="*60)
        print("  ⚠️  SOME TABLES STILL MISSING")
        print("="*60)
        print("\nTry these commands manually:")
        print("  python manage.py makemigrations")
        print("  python manage.py migrate --run-syncdb")
        print("  python manage.py migrate --fake-initial")

if __name__ == '__main__':
    main()
