#!/usr/bin/env python3
"""
Script pour vérifier et forcer la mise à jour du flag network_device
"""
import os
import sys

# Ajouter le chemin parent pour les imports
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.app.models.ip import IP

# Créer la connexion à la base de données
db_path = os.getenv('DB_PATH', './data/db.sqlite')
db_url = f"sqlite:///{db_path}"
engine = create_engine(db_url, echo=False)
SessionLocal = sessionmaker(bind=engine)

db = SessionLocal()

try:
    # Récupérer toutes les IPs
    ips = db.query(IP).all()

    print(f"\n📊 Total IPs: {len(ips)}\n")

    updated = 0
    for ip in ips:
        # Afficher les IPs avec host défini
        if ip.host:
            status_icon = "🟢" if ip.last_status == "online" else "🔴"
            network_icon = "🔷" if ip.network_device else "  "

            print(f"{status_icon} {network_icon} {ip.ip:15s} | Host: {ip.host:15s} | Network: {ip.network_device} | Status: {ip.last_status}")

            # Mettre à jour network_device si host == "Network"
            should_be_network = (ip.host == "Network")
            if ip.network_device != should_be_network:
                ip.network_device = should_be_network
                updated += 1
                print(f"   ✓ Flag network_device mis à jour pour {ip.ip}: {should_be_network}")

    if updated > 0:
        db.commit()
        print(f"\n✅ {updated} IP(s) mise(s) à jour!")
    else:
        print(f"\n✓ Tous les flags network_device sont déjà à jour")

except Exception as e:
    print(f"❌ Erreur: {e}")
    import traceback
    traceback.print_exc()
finally:
    db.close()
