import logging
import sys

log = logging.getLogger("topovec")


def configLog(level=logging.DEBUG):
    global log
    log.setLevel(level)
    log.propagate = False

    for handler in log.handlers:
        if getattr(handler, "_topovec_console_handler", False):
            handler.setLevel(level)
            return log

    try:
        from rich.console import Console
        from rich.logging import RichHandler

        handler = RichHandler(
            rich_tracebacks=True,
            console=Console(stderr=True),
            show_path=False,
        )
    except Exception:
        handler = logging.StreamHandler(sys.stderr)
        handler.setFormatter(
            logging.Formatter(
                fmt="%(asctime)s %(levelname)s %(name)s: %(message)s",
                datefmt="%H:%M:%S",
            )
        )
    handler.setLevel(level)
    handler._topovec_console_handler = True
    log.addHandler(handler)
    return log
