#!/usr/bin/env python3
"""
Migration 017: Ajout des champs Proxmox
"""
import sqlite3
import sys
from pathlib import Path

# Configuration
DB_PATH = Path(__file__).parent / "data" / "data.db"
MIGRATION_FILE = Path(__file__).parent / "migrations" / "017_add_proxmox_fields.sql"

def main():
    if not DB_PATH.exists():
        print(f"❌ Base de données non trouvée: {DB_PATH}")
        sys.exit(1)

    # Lire le fichier SQL
    with open(MIGRATION_FILE, 'r') as f:
        sql = f.read()

    # Connexion à la BDD
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    try:
        # Vérifier si les colonnes existent déjà
        cursor.execute("PRAGMA table_info(hardware_snapshots)")
        columns = [col[1] for col in cursor.fetchall()]

        existing = []
        if 'is_proxmox_host' in columns:
            existing.append('is_proxmox_host')
        if 'is_proxmox_guest' in columns:
            existing.append('is_proxmox_guest')
        if 'proxmox_version' in columns:
            existing.append('proxmox_version')

        if len(existing) == 3:
            print("✅ Toutes les colonnes Proxmox existent déjà")
            return
        elif existing:
            print(f"⚠️  Colonnes existantes: {', '.join(existing)}")

        # Appliquer la migration
        print("🔧 Application de la migration 017...")
        cursor.executescript(sql)
        conn.commit()
        print("✅ Migration 017 appliquée avec succès")

        # Vérifier
        cursor.execute("PRAGMA table_info(hardware_snapshots)")
        columns_after = [col[1] for col in cursor.fetchall()]

        success = True
        for col in ['is_proxmox_host', 'is_proxmox_guest', 'proxmox_version']:
            if col in columns_after:
                print(f"✅ Colonne {col} ajoutée")
            else:
                print(f"❌ Erreur: colonne {col} non ajoutée")
                success = False

        if not success:
            sys.exit(1)

    except Exception as e:
        print(f"❌ Erreur lors de la migration: {e}")
        conn.rollback()
        sys.exit(1)
    finally:
        conn.close()

if __name__ == "__main__":
    main()
