"""
Script de migration pour ajouter les champs 'icon_filename' et 'icon_url' à la table IP
Exécuter avec: python -m backend.app.migrations.add_icon_fields
"""
from sqlalchemy import text, create_engine
import sys
import os


def migrate():
    try:
        db_path = os.getenv('DB_PATH', './data/db.sqlite')
        db_url = f"sqlite:///{db_path}"
        engine = create_engine(db_url, echo=False)

        with engine.connect() as conn:
            result = conn.execute(text("PRAGMA table_info(ip)"))
            columns = [row[1] for row in result]

            if 'icon_filename' not in columns:
                print("→ Ajout de la colonne 'icon_filename'...")
                conn.execute(text("ALTER TABLE ip ADD COLUMN icon_filename TEXT"))
                conn.execute(text("CREATE INDEX IF NOT EXISTS idx_ip_icon_filename ON ip(icon_filename)"))
            else:
                print("✓ Colonne 'icon_filename' déjà présente")

            if 'icon_url' not in columns:
                print("→ Ajout de la colonne 'icon_url'...")
                conn.execute(text("ALTER TABLE ip ADD COLUMN icon_url TEXT"))
                conn.execute(text("CREATE INDEX IF NOT EXISTS idx_ip_icon_url ON ip(icon_url)"))
            else:
                print("✓ Colonne 'icon_url' déjà présente")

            conn.commit()
            print("✓ Migration terminée avec succès")

    except Exception as e:
        print(f"✗ Erreur lors de la migration: {str(e)}", file=sys.stderr)
        sys.exit(1)


def rollback():
    try:
        print("⚠ Rollback non implémenté pour SQLite")
    except Exception as e:
        print(f"✗ Erreur lors du rollback: {str(e)}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "rollback":
        rollback()
    else:
        migrate()
