import logging
import io
import sys


def setup_logging():
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.WARNING)

    stream = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
    handler = logging.StreamHandler(stream)
    handler.setLevel(logging.WARNING)
    formatter = logging.Formatter(
        "%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
    )
    handler.setFormatter(formatter)
    root_logger.addHandler(handler)


setup_logging()
logger = logging.getLogger(__name__)

LOG_LEVELS = {
    "DEBUG": logging.DEBUG,
    "INFO": logging.INFO,
    "WARNING": logging.WARNING,
    "ERROR": logging.ERROR,
    "CRITICAL": logging.CRITICAL,
}


def set_log_level(level: str) -> bool:
    level_upper = level.upper()
    if level_upper not in LOG_LEVELS:
        return False
    root_logger = logging.getLogger()
    root_logger.setLevel(LOG_LEVELS[level_upper])
    for handler in root_logger.handlers:
        handler.setLevel(LOG_LEVELS[level_upper])
    return True
