import json
from netmiko import ConnectHandler

def question_9(net_connect):
    print(net_connect.__dict__)
    print("Adresse IP :", net_connect.host)
    print("Device type :", net_connect.device_type)


def question_10(net_connect):
    output = net_connect.send_command("show ip interface brief")
    print(output)

def question_11(net_connect):
    output = net_connect.send_command("show ip interface brief", use_textfsm=True)
    print(type(output))

def question_12(net_connect):
    pass

def question_13(net_connect):
    output = net_connect.send_command("show ip route", use_textfsm=True)
    print(output)
    print(type(output))


def question_14(net_connect):
    interfaces_status = net_connect.send_command("show ip interface brief", use_textfsm=True)
    print("État des interfaces du routeur R1 :")
    #print(interfaces_status)

    for iface in interfaces_status:
        intf_name = iface['interface']
        print(f"\nConfiguration de l'interface {intf_name} :")
        config = net_connect.send_command(f"show run interface {intf_name}")
        print(config)



def question_15(net_connect):
    # Liste de commandes pour créer l'interface Loopback
    loopback_cmds = [
        "interface loopback1",
        "ip address 192.168.1.1 255.255.255.255",
        "description loopback interface from netmiko",
        "no shutdown"
    ]

    # Exécution des commandes en mode configuration
    output = net_connect.send_config_set(loopback_cmds)
    print("Résultat de la configuration :")
    print(output)

    # Sauvegarder la configuration
    save_output = net_connect.save_config()
    print("\nConfiguration sauvegardée :")
    print(save_output)

def question_16(net_connect):
    # Exécution en mode configuration
    output = net_connect.send_config_set("no interface loopback1")
    print("Résultat de la suppression de loopback1 :")
    print(output)

    # Sauvegarder la configuration
    save_output = net_connect.save_config()
    print("\nConfiguration sauvegardée après suppression :")
    print(save_output)


def question_17(net_connect):
    # Lire les commandes depuis le fichier
    with open("config/loopback_R01.conf", "r") as f:
        commands = [line.strip() for line in f if line.strip()]  # ignore les lignes vides

    # Exécuter les commandes en mode configuration
    output = net_connect.send_config_set(commands)
    print("Résultat de l'exécution des commandes :")
    print(output)

    # Sauvegarder la configuration
    save_output = net_connect.save_config()
    print("\nConfiguration sauvegardée :")
    print(save_output)

def question_18(net_connect):
    for i in range(1, 5):
        loopback_name = f"loopback{i}"
        commands = [f"no interface {loopback_name}"]
        print(f"\nSuppression de l'interface {loopback_name} :")
        output = net_connect.send_config_set(commands)
        print(output)
    # Sauvegarder la configuration
    save_output = net_connect.save_config()
    print("\nConfiguration sauvegardée :")
    print(save_output)

def get_inventory():
    """
    Lit le fichier inventory/hosts.json et retourne son contenu.
    """
    inventory_file = "inventory/hosts.json"
    try:
        with open(inventory_file, "r") as f:
            data = json.load(f)
        return data
    except FileNotFoundError:
        print(f"Erreur : le fichier {inventory_file} n'existe pas.")
        return []


def question_20():
    pass


def question_21():
    inventory = get_inventory()

    for device in inventory:
        print(f"\n=== Connexion au routeur {device['hostname']} ({device['ip']}) ===")

        try:
            # Connexion au routeur
            net_connect = ConnectHandler(
                device_type=device["device_type"],
                host=device["ip"],
                username=device["username"],
                password=device["password"]
            )

            # Commande à exécuter
            command = "show run interface GigabitEthernet0/0.99"
            output = net_connect.send_command(command)

            print(f"\nConfiguration de GigabitEthernet0/0.99 sur {device['hostname']} :\n")
            print(output)

            net_connect.disconnect()

        except Exception as e:
            print(f"❌ Erreur sur {device['hostname']} : {e}")
def question_22():
    inventory = get_inventory()

    for device in inventory:
        # On ne traite pas les routeurs dont le hostname != 'R1' de ESW1
        if 'R1' == device["hostname"] or 'ESW1' == device["hostname"]:
            continue

        print(f"\n=== Connexion au routeur {device['hostname']} ({device['ip']}) ===")

        try:
            # Paramètres de connexion
            device_params = {
                'device_type': device['device_type'],
                'host': device['ip'],
                'username': device['username'],
                'password': device['password']
            }
            net_connect = ConnectHandler(**device_params)
            net_connect.enable()

            # affiche le hostname
            print(f"Connexion réussie sur {device['hostname']}")

            config_file = f'config/vlan_{device["hostname"]}.conf'
            output = net_connect.send_config_from_file(config_file)
            print(f"\nRésultat de l'application de la configuration sur {device['hostname']} :\n{output}")

            # Sauvegarde la configuration
            save_output = net_connect.save_config()
            print(f"\nSauvegarde de la configuration sur {device['hostname']} :\n{save_output}")

            net_connect.disconnect()

        except Exception as e:
            print(f"❌ Erreur sur {device['hostname']} : {e}")

if __name__ == "__main__":    

 
    #question_9(net_connect)
    #question_10(net_connect)
    #question_11(net_connect)
    #question_12(net_connect)
    #question_13(net_connect)
    #question_14(net_connect)
    #question_15(net_connect)
    #question_16(net_connect)
    #question_17(net_connect)
    #question_18(net_connect)
    hosts = get_inventory()
    #print(hosts)
    #question_20()
    #question_21()
    question_22()