#!/usr/bin/env python3
"""
Test script to verify that init_db() creates all tables and indexes properly.
This simulates a fresh database initialization.
"""
import asyncio
import sys
import os
sys.path.insert(0, '/app')
from api import database

async def test_init():
    """Test database initialization"""
    print("Testing database initialization...")
    print("=" * 60)
    
    try:
        # Initialize database (create tables and indexes)
        await database.init_db()
        print("✓ Database initialization completed successfully")
        
        # Verify tables exist
        async with database.engine.begin() as conn:
            result = await conn.execute(database.text("""
                SELECT tablename 
                FROM pg_tables 
                WHERE schemaname = 'public' 
                ORDER BY tablename;
            """))
            tables = [row[0] for row in result]
            print(f"\n✓ Found {len(tables)} tables:")
            for table in tables:
                print(f"  - {table}")
            
            # Verify indexes exist
            result = await conn.execute(database.text("""
                SELECT tablename, indexname 
                FROM pg_indexes 
                WHERE schemaname = 'public' AND indexname LIKE 'idx_%'
                ORDER BY tablename, indexname;
            """))
            indexes = list(result)
            print(f"\n✓ Found {len(indexes)} performance indexes:")
            for table, index in indexes:
                print(f"  - {index} on {table}")
        
        print("\n" + "=" * 60)
        print("✓ All tests passed!")
        return True
        
    except Exception as e:
        print(f"\n✗ Error during initialization: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        await database.engine.dispose()

if __name__ == "__main__":
    success = asyncio.run(test_init())
    sys.exit(0 if success else 1)
