#!/usr/bin/env python3
"""
Migration: Add last_action field to pvp_combats table
This allows the opponent to see what happened in the last turn
"""

import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text

async def migrate():
    """Add last_action column to pvp_combats table"""
    
    # Database connection details
    db_host = os.getenv('DB_HOST', 'localhost')
    db_port = os.getenv('DB_PORT', '5432')
    db_name = os.getenv('DB_NAME', 'echoes_db')
    db_user = os.getenv('DB_USER', 'echoes_user')
    db_password = os.getenv('DB_PASSWORD', 'change_this_password')
    
    # Create async engine
    database_url = f"postgresql+asyncpg://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
    engine = create_async_engine(database_url, echo=False)
    
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        try:
            # Add last_action column to pvp_combats
            await session.execute(text("""
                ALTER TABLE pvp_combats 
                ADD COLUMN IF NOT EXISTS last_action TEXT DEFAULT NULL;
            """))
            
            await session.commit()
            print("✅ Added last_action column to pvp_combats table")
            
        except Exception as e:
            await session.rollback()
            print(f"❌ Error: {e}")
            raise
        finally:
            await engine.dispose()

if __name__ == "__main__":
    asyncio.run(migrate())
    print("✅ Migration completed successfully!")
