"""
Script de migration pour ajouter la table architecture_node
Exécuter avec: python -m backend.app.migrations.add_architecture_node_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='architecture_node'"))
            if result.fetchone():
                print("✓ Table 'architecture_node' existe déjà")
                return

            print("→ Création de la table 'architecture_node'...")
            conn.execute(text("""
                CREATE TABLE architecture_node (
                    id TEXT PRIMARY KEY,
                    type TEXT NOT NULL,
                    x INTEGER NOT NULL,
                    y INTEGER NOT NULL,
                    width INTEGER NOT NULL,
                    height INTEGER NOT NULL,
                    rotation INTEGER NOT NULL,
                    payload TEXT NOT NULL,
                    created_at DATETIME NOT NULL
                )
            """))
            conn.execute(text("CREATE INDEX IF NOT EXISTS idx_arch_node_created_at ON architecture_node(created_at)"))
            conn.commit()
            print("✓ Table 'architecture_node' créée")

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