#!/usr/bin/env python
"""
Create all users app tables
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.apps import apps
from django.db import connection

print("Creating users app tables...")
print("=" * 60)

# Get users app models
users_app = apps.get_app_config('users')
models = list(users_app.get_models())

print(f"\nFound {len(models)} models in users app:")
for model in models:
    print(f"  - {model.__name__} -> {model._meta.db_table}")

print("\n" + "=" * 60)
print("Creating tables...")

with connection.schema_editor() as schema_editor:
    for model in models:
        table_name = model._meta.db_table
        
        with connection.cursor() as cursor:
            cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
            exists = cursor.fetchone()
            
            if not exists:
                try:
                    schema_editor.create_model(model)
                    print(f"  ✓ Created {table_name}")
                except Exception as e:
                    print(f"  ⚠ Error creating {table_name}: {e}")
            else:
                print(f"  - {table_name} already exists")

print("\n" + "=" * 60)

# Verify tables were created
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    all_tables = [t[0] for t in cursor.fetchall()]
    user_tables = [t for t in all_tables if 'user' in t.lower() or t in ['branches', 'default_role_permissions', 'role_permissions']]
    
    print(f"\nUser-related tables now in database: {len(user_tables)}")
    for table in sorted(user_tables):
        print(f"  ✓ {table}")

print("\n" + "=" * 60)
print("Done!")
