import time
from sp import bellman_ford, get_max, get_path

def main():
    # Read graph and global information from text file
    graphs = read_graphs_from_file("random_graphs.txt")

    run_random_test(graphs)


def write_to_file(info, execution_time):
    file_name = "results.txt"
    n, nb_nodes, links_size, min_cost, max_cost = info
    
    try:
        file_exists = False

        with open(file_name, 'r'):
            file_exists = True
    except FileNotFoundError:
        pass
    
    with open(file_name, 'a') as file:
        if not file_exists:
            file.write("Number of iterations, Number of nodes, Links size, Source node, Minimum cost, Maximum cost, Average Time per iteration, Density (links/node)\n")
        file.write(f"{n} {nb_nodes} {links_size} {min_cost} {max_cost} {execution_time:.8f} {links_size/nb_nodes} \n")



def read_graphs_from_file(file_path):
    graphs = []

    with open(file_path, 'r') as file:
        lines = file.readlines()

        graph = []
        global_info = []

        for line in lines:
            line = line.strip()

            if line == "=====":
                # End of the current graph, append it to the list of graphs and start a new one
                if graph:
                    graphs.append([global_info] + graph)

                graph = []
                global_info = []
            else:
                data = list(map(int, line.split(' ')))

                if not global_info:
                    # Read the global information from the first line
                    global_info = data
                else:
                    # Read the edge information and add it to the current graph
                    graph.append(data)

        if graph:
            graphs.append([global_info] + graph)
            

        return graphs


def run_random_test(graphs):
    total_time = 0
    count = 0
    last_global_info = None

    for links in graphs:
        # print(links)
        output_fd = open("temp.bin", "wb")
        nb_nodes = links[0][1]
        
        start_time = time.perf_counter()
        output_fd.write(nb_nodes.to_bytes(4, "big"))

        for source in range(nb_nodes):
            dist, path = bellman_ford(links[1:], source, nb_nodes, False)
            output_fd.write(source.to_bytes(4, "big"))
            d, n = get_max(dist, source)
            output_fd.write(n.to_bytes(4, "big"))
            output_fd.write(d.to_bytes(8, "big", signed=True))
            r = get_path(n, path, source)
            output_fd.write(len(r).to_bytes(4, "big", signed=True))
            for j in range(len(r)):
                output_fd.write(r[j].to_bytes(4, "big"))

        end_time = time.perf_counter()
        total_time += end_time - start_time

        if last_global_info is None:
            last_global_info = links[0]
        elif last_global_info != links[0]:
            print(last_global_info)
            print(last_global_info[0])
            print(total_time)
            execution_time = total_time / last_global_info[0]
            write_to_file(last_global_info, execution_time)
            last_global_info = links[0]
            total_time = 0
            count = 0
            print(execution_time)

        count += 1
        


    if count > 0:  # write the last result
        execution_time = total_time / last_global_info[0]
        write_to_file(last_global_info, execution_time)
        


    print("The results have been added to the 'results.txt' file.")

    return

    
if __name__ == "__main__":
    main()