from nornir import InitNornir
from nornir.core.task import Task, Result
from nornir_utils.plugins.functions import print_result
from nornir_napalm.plugins.tasks import napalm_get,napalm_configure, napalm_cli
from nornir_netmiko.tasks import netmiko_send_config,netmiko_send_command, netmiko_save_config, netmiko_commit

def question_13(nr):
    for key in nr.__dict__.keys():
        print(f"  - {key}")

def question_14(nr):
    print(nr.inventory.hosts)
    print(type(nr.inventory.hosts))

def question_15(nr):
    print(nr.inventory.hosts["R1-CPE-BAT-A"])
    print(type(nr.inventory.hosts["R1-CPE-BAT-A"]))

def question_16(nr):
    print(dir(nr.inventory.hosts["R1-CPE-BAT-A"]))
    first_host = list(nr.inventory.hosts.values())[0]
    print(f"Adresse IP (hostname): {first_host.hostname}")
    print(f"Username: {first_host.username}")
    print(f"Password: {first_host.password}")

def question_17(nr):
    print(dir(nr.inventory.hosts["R1-CPE-BAT-A"]))

def question_18(nr):
    print(nr.inventory.hosts["R1-CPE-BAT-A"].data["room"])

def question_19(nr):
    print(nr.inventory.groups)


def question_20(nr):
    print(nr.inventory.hosts.get('R1-CPE-BAT-A').groups)

def question_21(nr):
    print(nr.inventory.hosts.get('R1-CPE-BAT-A').groups[0].keys())

def question_22(nr):
    print(nr.inventory.hosts.get('R1-CPE-BAT-A').groups[0].get('vendor'))

def question_23(nr):
    for host_name in nr.inventory.hosts:
        print(nr.inventory.hosts.get(host_name).hostname)

def question_24(nr):
    print(nr.filter(device_type='router').inventory.hosts.keys())

def question_25(nr):
    print(nr.filter(device_type='router_switch').inventory.hosts.keys())

def hello_world(task: Task) -> Result:
    return Result(
    host=task.host,
    result=f"{task.host.name} says hello world!"
    )

def question_26(nr):
    result = nr.run(task=hello_world)
    print(result)

def question_27(nr):
    result = nr.run(task=hello_world)
    print(type(result))

def question_29(nr):
    result = nr.run(task=hello_world)
    print_result(result)

def question_30(nr):
    host = nr.filter(device_type='router_switch')
    print_result(host.run(task=hello_world))


def display_interfaces(task):
    task.run(
        task=napalm_cli,
        commands=["show ip interface brief"]
    )
def question_32(nr):
    filtre = nr.filter(device_type='router')
    result = filtre.run(task=display_interfaces)
    print_result(result)

def get_arp_table(task):
    task.run(
        task=napalm_get,
        getters=["arp_table"]
    )

def configure_loopback_r1(task):
    task.run(
        task=napalm_configure,
        configuration="""
interface Lo1
 ip address 1.1.1.1 255.255.255.255
 description Loopback pour R1-CPE-BAT-A
"""
    )

def configure_loopback_r2(task):
    task.run(
        task=napalm_configure,
        configuration="""
interface Lo1
 ip address 2.2.2.2 255.255.255.255
 description Loopback pour R2-CPE-BAT-A
"""
    )


def question_34(nr):
    R1 = nr.filter(name='R1-CPE-BAT-A')
    result_R1 = R1.run(task=configure_loopback_r1)
    R2 = nr.filter(name='R2-CPE-BAT-A')
    result_R2 = R2.run(task=configure_loopback_r2)
    print_result(result_R1)
    print_result(result_R2)

def save_running_config(task):
    # Exécute la commande de sauvegarde de la configuration
    task.run(
        task=napalm_cli,
        commands=["wr"]
    )

def question_35(nr):
    result = nr.run(task=save_running_config)
    print_result(result)

def question_36(nr):
    filtre = nr.filter(device_type='router')
    result = filtre.run(task=netmiko_send_command,command_string="show ip interface brief")
    print_result(result)
    
def configure_loopback2_r1(task):
    config_commands = [
        "interface loopback 2",
        "ip address 1.1.1.2 255.255.255.255",
        "description Loopback2 pour R1-CPE-BAT-A"
    ]
    task.run(task=netmiko_send_config, config_commands=config_commands)

def configure_loopback2_r2(task):
    config_commands = [
        "interface loopback 2",
        "ip address 2.2.2.3 255.255.255.255",
        "description Loopback2 pour R2-CPE-BAT-A"
    ]
    task.run(task=netmiko_send_config, config_commands=config_commands)

def question_37(nr):
    result_r1 = nr.filter(name='R1-CPE-BAT-A').run(task=configure_loopback2_r1)
    result_r2 = nr.filter(name='R2-CPE-BAT-A').run(task=configure_loopback2_r2)
    print_result(result_r1)
    print_result(result_r2)



def question_38(nr):
    filtreR1 = nr.filter(name='R1-CPE-BAT-A')
    resultR1 = filtreR1.run(task=netmiko_save_config)
    filtreR2 = nr.filter(name='R2-CPE-BAT-A')
    resultR2 = filtreR2.run(task=netmiko_save_config)
    print_result(resultR1)
    print_result(resultR2)
def deploy_config_from_file(task: Task, config_file: str) -> Result:
    """Déploie la configuration depuis un fichier sur un équipement via Nornir/Netmiko."""
    with open(config_file, "r") as f:
        commands = f.read().splitlines()
    result = task.run(task=netmiko_send_config, config_commands=commands)
    print_result(result)
    result = task.run(task=netmiko_save_config)
    print_result(result)
    return result

def deploy_to_hosts(nr, host_patterns):
    """Déploie les configurations pour tous les hôtes et ajoute le fichier VRRP pour les routers."""
    for pattern in host_patterns:
        # Filtrer uniquement par nom pour tous
        filtered_hosts = nr.filter(name=pattern)
        if not filtered_hosts.inventory.hosts:
            print(f"Aucun hôte correspondant à '{pattern}'")
            continue
        
        for host_name, host_obj in filtered_hosts.inventory.hosts.items():
            # Nom de fichier principal
            filename = host_obj.name.replace("-", "_").replace("CPE", "CPE_LYON")
            
            # Déploiement du fichier principal
            filtered_hosts.run(
                task=deploy_config_from_file,
                config_file=f"config/{filename}.conf",
                name=f"Déploiement config {host_obj.name}"
            )
    
    # Déploiement des fichiers VRRP uniquement pour les routers
    routers = nr.filter(device_type='router')
    for host_name, host_obj in routers.inventory.hosts.items():
        vrrp_filename = host_obj.name.replace("-", "_").replace("CPE", "CPE_LYON") + "_VRRP.conf"
        routers.run(
            task=deploy_config_from_file,
            config_file=f"config/{vrrp_filename}",
            name=f"Déploiement VRRP {host_obj.name}"
        )
        
def question_39(nr):
    host_patterns = [
        'R1-CPE-BAT-A',
        'R2-CPE-BAT-A',
        'R1-CPE-BAT-B',
        'R2-CPE-BAT-B',
        'ESW1-CPE-BAT-A',
        'ESW1-CPE-BAT-BS'
    
    ]
    deploy_to_hosts(nr, host_patterns)

def question_39_d(nr):
    pass

def question_40(nr):
    pass
    

if __name__ == "__main__":
    nr = InitNornir(config_file="inventory/config.yaml")

    #question_13(nr)
    #question_14(nr)
    #question_15(nr)
    #question_16(nr)
    #question_17(nr)
    #question_18(nr)
    #question_19(nr)
    #question_20(nr)
    #question_21(nr)
    #question_22(nr)
    #question_23(nr)
    #question_24(nr)
    #question_25(nr)
    #question_26(nr)
    #question_27(nr)
    #question_29(nr)
    #question_30(nr)

    #question_32(nr)
    #question_33(nr)
    #question_34(nr)
    #question_35(nr)
    #question_36(nr)
    #question_37(nr)
    #question_38(nr)
    question_39(nr)
    #question_39_d(nr)

    #question_40(nr)
    pass
