#!/usr/bin/env python3
"""
Check tables in system and gamification schemas.
"""
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text

async def check():
    from app.core.config import settings
    engine = create_async_engine(str(settings.SQLALCHEMY_DATABASE_URI))
    
    async with engine.begin() as conn:
        # List tables
        result = await conn.execute(text("""
            SELECT table_schema, table_name, 
                   (SELECT count(*) FROM information_schema.columns c WHERE c.table_schema=t.table_schema AND c.table_name=t.table_name) as column_count
            FROM information_schema.tables t
            WHERE table_name IN ('competitions', 'user_scores') 
            ORDER BY table_schema;
        """))
        rows = result.fetchall()
        print("Tables found:")
        for row in rows:
            print(f"  {row.table_schema}.{row.table_name} ({row.column_count} columns)")
            # Count rows
            count_result = await conn.execute(text(f'SELECT COUNT(*) FROM "{row.table_schema}"."{row.table_name}"'))
            count = count_result.scalar()
            print(f"    Rows: {count}")
        
        # Check foreign keys
        result = await conn.execute(text("""
            SELECT conname, conrelid::regclass as source_table, confrelid::regclass as target_table
            FROM pg_constraint
            WHERE contype = 'f' 
            AND (conrelid::regclass::text LIKE '%competitions%' OR conrelid::regclass::text LIKE '%user_scores%'
                 OR confrelid::regclass::text LIKE '%competitions%' OR confrelid::regclass::text LIKE '%user_scores%');
        """))
        fks = result.fetchall()
        print("\nForeign keys involving these tables:")
        for fk in fks:
            print(f"  {fk.conname}: {fk.source_table} -> {fk.target_table}")
    
    await engine.dispose()

if __name__ == "__main__":
    asyncio.run(check())