#!/usr/bin/env python3
"""
Move tables from system schema to gamification schema.
"""
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text

async def move_tables():
    # Use the same DATABASE_URL as sync_engine
    from app.core.config import settings
    engine = create_async_engine(str(settings.SQLALCHEMY_DATABASE_URI))
    
    async with engine.begin() as conn:
        # Check if tables exist in system schema
        result = await conn.execute(text("""
            SELECT table_schema, table_name 
            FROM information_schema.tables 
            WHERE table_name IN ('competitions', 'user_scores') 
            ORDER BY table_schema;
        """))
        rows = result.fetchall()
        print("Current tables:")
        for row in rows:
            print(f"  {row.table_schema}.{row.table_name}")
        
        # Move competitions
        print("\nMoving system.competitions to gamification.competitions...")
        try:
            await conn.execute(text('ALTER TABLE system.competitions SET SCHEMA gamification;'))
            print("  OK")
        except Exception as e:
            print(f"  Error: {e}")
        
        # Move user_scores
        print("Moving system.user_scores to gamification.user_scores...")
        try:
            await conn.execute(text('ALTER TABLE system.user_scores SET SCHEMA gamification;'))
            print("  OK")
        except Exception as e:
            print(f"  Error: {e}")
        
        # Verify
        result = await conn.execute(text("""
            SELECT table_schema, table_name 
            FROM information_schema.tables 
            WHERE table_name IN ('competitions', 'user_scores') 
            ORDER BY table_schema;
        """))
        rows = result.fetchall()
        print("\nAfter moving:")
        for row in rows:
            print(f"  {row.table_schema}.{row.table_name}")
    
    await engine.dispose()

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