import re


def expand_node_subsitute(arg, hist_obj):
    """
    Expand the subsitution for node PK in the argument.
    {} expands to node_history[current_pos].pk
    {n} expands to node_history[current_pos + n].pk
    """
    regex = r"{([-\d]*)}"
    for occ in re.finditer(regex, arg):
        whole_str = occ.group(0)
        if occ.group(1):
            idx = int(occ.group(1))
        else:
            idx = 0
        pointer = hist_obj.node_history_pointer + idx
        try:
            node = hist_obj.node_history[pointer][0]
        except IndexError:
            raise RuntimeError('Invalid offset {} in argument {}'.format(
                pointer, arg))
        # Replace the line
        else:
            arg = arg.replace(whole_str, str(node.args))

    return arg