#!/usr/bin/env python
"""
Final check and fix for all 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("=" * 60)
print("FINAL TABLE VERIFICATION")
print("=" * 60)

# Get all models from all apps
all_apps = ['users', 'loans', 'payments', 'reports', 'expenses', 'utils']
total_models = 0
total_tables = 0
missing_tables = []

for app_name in all_apps:
    try:
        app = apps.get_app_config(app_name)
        models = list(app.get_models())
        total_models += len(models)
        
        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 exists:
                    total_tables += 1
                else:
                    missing_tables.append((app_name, model.__name__, table_name))
    except Exception as e:
        print(f"Error checking {app_name}: {e}")

print(f"\nTotal models: {total_models}")
print(f"Total tables: {total_tables}")
print(f"Missing tables: {len(missing_tables)}")

if missing_tables:
    print("\nMissing tables:")
    for app, model, table in missing_tables:
        print(f"  ✗ {app}.{model} -> {table}")
else:
    print("\n✓ All tables exist!")

# Check critical tables for login
print("\n" + "=" * 60)
print("CRITICAL TABLES CHECK")
print("=" * 60)

critical = [
    'users',
    'users_branch',
    'role_permissions',
    'loans',
    'loan_applications',
    'loan_products',
    'expenses',
    'utils_systemsetting',
    'utils_notification',
]

with connection.cursor() as cursor:
    for table in critical:
        cursor.execute(f"SHOW TABLES LIKE '{table}'")
        exists = cursor.fetchone()
        status = "✓" if exists else "✗"
        print(f"  {status} {table}")

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