import logging
import os


FFX_LOGGER_NAME = "FFX"
CONSOLE_HANDLER_NAME = "ffx-console"
FILE_HANDLER_NAME = "ffx-file"


def get_ffx_logger(name: str = FFX_LOGGER_NAME) -> logging.Logger:
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    if not logger.handlers:
        logger.addHandler(logging.NullHandler())

    return logger


def configure_ffx_logger(
    log_file_path: str,
    file_level: int,
    console_level: int,
    name: str = FFX_LOGGER_NAME,
) -> logging.Logger:
    logger = get_ffx_logger(name)
    logger.propagate = False

    for handler in list(logger.handlers):
        if isinstance(handler, logging.NullHandler):
            logger.removeHandler(handler)

    console_handler = next(
        (handler for handler in logger.handlers if handler.get_name() == CONSOLE_HANDLER_NAME),
        None,
    )
    if console_handler is None:
        console_handler = logging.StreamHandler()
        console_handler.set_name(CONSOLE_HANDLER_NAME)
        logger.addHandler(console_handler)

    console_handler.setLevel(console_level)
    console_handler.setFormatter(logging.Formatter("%(message)s"))

    normalized_log_path = os.path.abspath(log_file_path)
    file_handler = next(
        (handler for handler in logger.handlers if handler.get_name() == FILE_HANDLER_NAME),
        None,
    )
    if (
        file_handler is not None
        and os.path.abspath(file_handler.baseFilename) != normalized_log_path
    ):
        logger.removeHandler(file_handler)
        file_handler.close()
        file_handler = None

    if file_handler is None:
        file_handler = logging.FileHandler(normalized_log_path)
        file_handler.set_name(FILE_HANDLER_NAME)
        logger.addHandler(file_handler)

    file_handler.setLevel(file_level)
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    )

    return logger
