import logging as lg

from rdkit.rdBase import LogToPythonLogger


def handle_rdkit_logging():
    """from https://greglandrum.github.io/rdkit-blog/posts/2024-02-23-custom-transformations-and-logging.html

    Example:
        ```python
        #N normalize a molecule:

        m2 = nrm2.normalize(m)

        We don’t see anything in the notebook because the main handler (the one which goes to the console/notebook) is still set to only show WARN and above, but logger_sio has the message:

        text = logger_sio.getvalue()
        print(text)

        [06:20:44] Running Normalizer
        [06:20:44] Rule applied: remove_Boc
        [06:20:44] Rule applied: disconnect_alkali_metals


        # we can reset the StringIO object:

        logger_sio.truncate(0)
        logger_sio.seek(0)

        # Create and normalize a new molecule:
        new_m = Chem.MolFromSmiles('CCCO[Na]')
        new_m2 = nrm2.normalize(new_m)

        # show the normalizations that were applied:
        re.findall(r'Rule applied: (.*?)\n',logger_sio.getvalue())
        ```

    """
    logger = lg.getLogger("rdkit")
    logger.handlers[0].setLevel(lg.WARN)
    logger.handlers[0].setFormatter(lg.Formatter("[RDKit] %(levelname)s:%(message)s"))
    # Tell the RDKit's C++ backend to log to use the python logger:
    LogToPythonLogger()
    from io import StringIO

    logger = lg.getLogger("rdkit")
    logger_sio = StringIO()
    # create a handler that uses the StringIO and set its log level:
    handler = lg.StreamHandler(logger_sio)
    handler.setLevel(lg.INFO)

    logger.addHandler(handler)
    logger.setLevel(lg.INFO)
    return logger, logger_sio


handle_rdkit_logging()
