#!/usr/bin/env python
"""
Create missing utils app tables
"""
import os
import django

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

from django.db import connection
from django.core.management import call_command

print("Checking for missing utils tables...")
print("=" * 60)

with connection.cursor() as cursor:
    # Check which utils tables exist
    cursor.execute("SHOW TABLES LIKE 'utils_%'")
    existing_tables = [table[0] for table in cursor.fetchall()]
    
    print(f"\nExisting utils tables: {len(existing_tables)}")
    for table in existing_tables:
        print(f"  ✓ {table}")
    
    # Expected utils tables based on models
    expected_tables = [
        'utils_notification',
        'utils_systemsetting',
        'utils_auditlog',
        'utils_document',
        'utils_documentshare',
        'utils_receipt',
    ]
    
    missing_tables = [t for t in expected_tables if t not in existing_tables]
    
    if missing_tables:
        print(f"\nMissing tables: {len(missing_tables)}")
        for table in missing_tables:
            print(f"  ✗ {table}")
        
        print("\nCreating missing tables...")
        
        # Run migrations for utils app
        try:
            call_command('migrate', 'utils', '--run-syncdb', verbosity=2)
            print("\n✓ Tables created successfully")
        except Exception as e:
            print(f"\n⚠ Error creating tables: {e}")
            print("\nTrying alternative approach...")
            
            # Create tables manually
            from utils.models import SystemSetting, AuditLog, Document, DocumentShare, Receipt, Notification
            from django.db import connection
            from django.core.management.sql import sql_create
            
            # Get SQL for creating tables
            with connection.schema_editor() as schema_editor:
                for model in [SystemSetting, AuditLog, Document, DocumentShare, Receipt, Notification]:
                    try:
                        schema_editor.create_model(model)
                        print(f"  ✓ Created {model._meta.db_table}")
                    except Exception as e:
                        print(f"  ⚠ {model._meta.db_table}: {e}")
    else:
        print("\n✓ All expected tables exist")

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