"""
Migration script to add combat system columns to existing database.
Run this once to upgrade the database schema.
"""

import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
from dotenv import load_dotenv

async def migrate():
    load_dotenv()
    
    DB_USER = os.getenv("POSTGRES_USER")
    DB_PASS = os.getenv("POSTGRES_PASSWORD")
    DB_NAME = os.getenv("POSTGRES_DB")
    DB_HOST = os.getenv("POSTGRES_HOST")
    DB_PORT = os.getenv("POSTGRES_PORT")
    
    DATABASE_URL = f"postgresql+psycopg://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
    engine = create_async_engine(DATABASE_URL)
    
    print("Starting database migration...")
    
    async with engine.begin() as conn:
        # Add level column if it doesn't exist
        try:
            await conn.execute(text(
                "ALTER TABLE players ADD COLUMN level INTEGER DEFAULT 1"
            ))
            print("✅ Added 'level' column")
        except Exception as e:
            if "already exists" in str(e):
                print("⚠️  'level' column already exists, skipping")
            else:
                print(f"❌ Error adding 'level': {e}")
        
        # Add xp column if it doesn't exist
        try:
            await conn.execute(text(
                "ALTER TABLE players ADD COLUMN xp INTEGER DEFAULT 0"
            ))
            print("✅ Added 'xp' column")
        except Exception as e:
            if "already exists" in str(e):
                print("⚠️  'xp' column already exists, skipping")
            else:
                print(f"❌ Error adding 'xp': {e}")
        
        # Add unspent_points column if it doesn't exist
        try:
            await conn.execute(text(
                "ALTER TABLE players ADD COLUMN unspent_points INTEGER DEFAULT 0"
            ))
            print("✅ Added 'unspent_points' column")
        except Exception as e:
            if "already exists" in str(e):
                print("⚠️  'unspent_points' column already exists, skipping")
            else:
                print(f"❌ Error adding 'unspent_points': {e}")
        
        # Create active_combats table if it doesn't exist
        try:
            await conn.execute(text("""
                CREATE TABLE IF NOT EXISTS active_combats (
                    id SERIAL PRIMARY KEY,
                    player_id INTEGER UNIQUE REFERENCES players(telegram_id) ON DELETE CASCADE,
                    npc_id VARCHAR NOT NULL,
                    npc_hp INTEGER NOT NULL,
                    npc_max_hp INTEGER NOT NULL,
                    turn VARCHAR NOT NULL,
                    turn_started_at FLOAT NOT NULL,
                    player_status_effects VARCHAR DEFAULT '[]',
                    npc_status_effects VARCHAR DEFAULT '[]',
                    location_id VARCHAR NOT NULL
                )
            """))
            print("✅ Created 'active_combats' table")
        except Exception as e:
            print(f"⚠️  'active_combats' table: {e}")
        
        # Create player_corpses table if it doesn't exist
        try:
            await conn.execute(text("""
                CREATE TABLE IF NOT EXISTS player_corpses (
                    id SERIAL PRIMARY KEY,
                    player_name VARCHAR NOT NULL,
                    location_id VARCHAR NOT NULL,
                    items VARCHAR NOT NULL,
                    death_timestamp FLOAT NOT NULL
                )
            """))
            print("✅ Created 'player_corpses' table")
        except Exception as e:
            print(f"⚠️  'player_corpses' table: {e}")
        
        # Create npc_corpses table if it doesn't exist
        try:
            await conn.execute(text("""
                CREATE TABLE IF NOT EXISTS npc_corpses (
                    id SERIAL PRIMARY KEY,
                    npc_id VARCHAR NOT NULL,
                    location_id VARCHAR NOT NULL,
                    loot_remaining VARCHAR NOT NULL,
                    death_timestamp FLOAT NOT NULL
                )
            """))
            print("✅ Created 'npc_corpses' table")
        except Exception as e:
            print(f"⚠️  'npc_corpses' table: {e}")
    
    await engine.dispose()
    print("\n✅ Migration complete!")

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