#!/usr/bin/env python
"""
Create all missing 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 all missing app tables...")
print("=" * 60)

# Apps to check
app_names = ['loans', 'payments', 'reports', 'expenses']

for app_name in app_names:
    print(f"\n{app_name.upper()} APP:")
    print("-" * 60)
    
    try:
        app = apps.get_app_config(app_name)
        models = list(app.get_models())
        
        print(f"Found {len(models)} models")
        
        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"  ⚠ {table_name}: {str(e)[:80]}")
                    else:
                        print(f"  - {table_name} exists")
    except Exception as e:
        print(f"  ✗ Error with {app_name}: {e}")

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

# Final count
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    all_tables = [t[0] for t in cursor.fetchall()]
    print(f"\nTotal tables in database: {len(all_tables)}")

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