"""
Script de migration pour ajouter la table scan_log
Exécuter avec: python -m backend.app.migrations.add_scan_log_table
"""
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("SELECT name FROM sqlite_master WHERE type='table' AND name='scan_log'"))
            if result.fetchone():
                print("✓ Table 'scan_log' existe déjà")
                return

            print("→ Création de la table 'scan_log'...")
            conn.execute(text("""
                CREATE TABLE scan_log (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    ip TEXT,
                    status TEXT,
                    message TEXT NOT NULL,
                    created_at DATETIME NOT NULL
                )
            """))
            conn.execute(text("CREATE INDEX IF NOT EXISTS idx_scan_log_created_at ON scan_log(created_at)"))
            conn.execute(text("CREATE INDEX IF NOT EXISTS idx_scan_log_ip ON scan_log(ip)"))
            conn.commit()
            print("✓ Table 'scan_log' créée")

    except Exception as e:
        print(f"✗ Erreur migration scan_log: {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 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()
