import copy
import json
import os
import pandas as pd

def create_l1_topology():
    """Create the Layer1 topology."""

    # L1 topology input CSV generated by the Arista ansible playbook
    L1_INPUT = './documentation/DC1_FABRIC/DC1_FABRIC-topology.csv'
    # directory where batfish will look for the layer1 topology
    OUT_DIR = './intended/batfish/'
    topology_file = OUT_DIR + "/layer1_topology.json"

    # headers for the csv file generated by the Arista ansible playbook
    headers = 'Node Type,Node,Node Interface,Peer Type,Peer,Peer Interface'
    # if the folder named batfish doesn't exist, create it
    if not os.path.exists(OUT_DIR):
        print("Creating the batfish directory for the snapshot")
        os.makedirs(OUT_DIR)

    # read the CSV file generated by the Ansible role
    df = pd.read_csv(L1_INPUT)

    # l1 topology is a list of edges
    topology = {
        'edges': []
    }

    # edges are represented as a dict of dict
    empty_edge = {
        "node1": {
            "hostname": "",
            "interfaceName": ""
        },
        "node2": {
            "hostname": "",
            "interfaceName": ""
        }
    }

    for index, row in df.iterrows():
        new_edge = copy.deepcopy(empty_edge)
        new_edge['node1']['hostname'] = row['Node'].lower()
        new_edge['node1']['interfaceName'] = row['Node Interface']
        new_edge['node2']['hostname'] = row['Peer'].lower()
        new_edge['node2']['interfaceName'] = row['Peer Interface']

        topology['edges'].append(copy.deepcopy(new_edge))

    # write the l1 topology to file
    print("Writing L1 topology")
    with open(topology_file, 'w') as f:
        json.dump(topology, f)

def main():
    create_l1_topology()

if __name__ == '__main__':
    main()