"""
Add key_encrypted column to license_keys for platform admin key retrieval.

Run: python migrations/add_license_key_encrypted.py
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from sqlalchemy import text
from app.core.database import engine
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def column_exists(conn, table: str, column: str) -> bool:
    bind = engine.url.drivername
    if "sqlite" in bind:
        rows = conn.execute(text(f"PRAGMA table_info({table})")).fetchall()
        return any(r[1] == column for r in rows)
    result = conn.execute(
        text(
            "SELECT 1 FROM information_schema.columns "
            "WHERE table_name = :t AND column_name = :c"
        ),
        {"t": table, "c": column},
    )
    return result.fetchone() is not None


def run_migration():
    with engine.begin() as conn:
        if column_exists(conn, "license_keys", "key_encrypted"):
            logger.info("key_encrypted already exists — skipping")
            return
        logger.info("Adding license_keys.key_encrypted…")
        conn.execute(text("ALTER TABLE license_keys ADD COLUMN key_encrypted TEXT"))
        logger.info("Done.")


if __name__ == "__main__":
    run_migration()
