import sys; sys.path.append("/app")
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.db.models import Skill
from app.config import settings
import json

print("Starting skill features migration...")
try:
    engine = create_engine(settings.DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    with SessionLocal() as db:
        skills = db.query(Skill).all()
        updated_count = 0
        for skill in skills:
            if not skill.features:
                skill.features = ["swarm_control"]
                updated_count += 1
                continue
            
            features = list(skill.features)
            changed = False
            
            if "chat" in features:
                features.remove("chat")
                changed = True
            
            if "voice" in features:
                features.remove("voice")
                features.append("voice_chat")
                changed = True
                
            if "swarm" in features:
                features.remove("swarm")
                features.append("swarm_control")
                changed = True
                
            if "swarm_control" not in features and len(features) == 0:
                features.append("swarm_control")
                changed = True
            
            if "swarm_control" not in features and changed:
                # If they had chat but no swarm_control, we must add swarm_control
                features.append("swarm_control")

            if changed:
                # Deduplicate
                skill.features = list(set(features))
                updated_count += 1

        db.commit()
        print(f"Successfully migrated {updated_count} skills legacy feature mappings.")

except Exception as e:
    print(f"Exception formatting db: {e}")
