import logging


def compare_model_reactions(model1, model2):
    """
    This function compares two RMG models and returns a list of common reactions (with a nested list containing
    both reaction objects as elements), as well as a list of unique reactions for each model.
    """
    reaction_list1 = model1.reactions[:]
    reaction_list2 = model2.reactions[:]

    # remove reactions that have an unidentified species
    to_remove = []
    for reactionList in (reaction_list1, reaction_list2):
        for reaction in reactionList:
            for side in (reaction.products, reaction.reactants):
                for species in side:
                    if not species.molecule:
                        to_remove.append((reactionList, reaction))
                        logging.warning(
                            "Removing reaction {!r} that had unidentified species {!r}".format(reaction, species))
                        break
    for reactionList, reaction in to_remove:
        reactionList.remove(reaction)

    common_reactions = []
    unique_reactions1 = []
    unique_reactions2 = []
    for rxn1 in reaction_list1:
        for rxn2 in reaction_list2[:]:  # make a copy so you don't remove from the list you are iterating over
            if rxn1.is_isomorphic(rxn2):
                common_reactions.append([rxn1, rxn2])
                # Remove reaction 2 from being chosen a second time.
                # Let each reaction only appear only once in the diff comparison.
                # Otherwise this miscounts number of reactions in model 2.
                reaction_list2.remove(rxn2)
                break
    for rxn1 in reaction_list1:
        for r1, r2 in common_reactions:
            if rxn1 is r1:
                break
        else:
            unique_reactions1.append(rxn1)
    for rxn2 in reaction_list2:
        for r1, r2 in common_reactions:
            if rxn2 is r2:
                break
        else:
            unique_reactions2.append(rxn2)

    return common_reactions, unique_reactions1, unique_reactions2