import networkx as nx

from utils_proof.str import *

def frr_to_graph(frr):
    statement_list = frr.split('\n')
    statement_list = [s for s in statement_list if len(s) and s[0] != '#' and '=' in s and '[' in s and ']' in s and '(' in s and ')' in s]
    statement_list = [s.split('#')[0].strip() for s in statement_list]
    statement_list = [s for s in statement_list if not is_variable(s)]
    # statement_list = merge_lines(statement_list)
    statement_list = [convert_function_calls(s) for s in statement_list]
    statement_list = convert_to_function(statement_list)
    statement_list = unpack_statements(statement_list)
    statement_list = convert_to_function(statement_list)
    G = nx.DiGraph()
    statement_list = eliminate_loop(statement_list)
    for s in statement_list:
        flag, output = extract_parts(s)
        if flag == 'init':
            G.add_node(output)
        elif flag == 'operation':
            target, description, sources = output
            if 'given' in description or 'triple' in description:
                continue
            if target in G.nodes():
                target = target + '_NeW'
            for source in sources:
                if is_num(source):
                    G.add_node(source)
                if not G.has_edge(source, target):
                    G.add_edge(source, target, label=description)
    return G