from functools import reduce
import operator


def reaction_extraction_from_pathway(
    simulation_analyzer, target_id, num_paths=100, sort_by="weight"
):
    """
    Method to extract reaction ids from the pathways
    :param simulation_analyzer: SimulationAnalyzer object
    :param target_id: speices id to path find to
    :param num_paths: number of paths to extract reactions from
    :param sort_by: sort top pathways by frequency or weight
    :return: all_reactions: list of reaction ids
    """

    simulation_analyzer.extract_reaction_pathways(target_id)
    reaction_dict = simulation_analyzer.reaction_pathways_dict[target_id]
    if reaction_dict == {}:
        return "No paths to " + str(target_id)
    else:
        paths = list(reaction_dict.keys())
        if sort_by == "weight":
            paths_sorted = sorted(
                paths,
                key=lambda x: (
                    reaction_dict[x]["weight"],
                    reaction_dict[x]["frequency"],
                ),
            )
        else:
            paths_sorted = sorted(
                paths,
                key=lambda x: (
                    reaction_dict[x]["frequency"],
                    reaction_dict[x]["weight"],
                ),
            )
        paths_sorted = [list(x) for x in paths_sorted]
        top_paths_sorted = [list(x) for x in paths_sorted][0:num_paths]
        all_reactions = list(set(reduce(operator.concat, top_paths_sorted)))

        return all_reactions