import logging
import io
import sys

from aiohttp import ClientError, ClientResponse

from sds_mng.exception import UnauthorizedError

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

def raise_for_status(resp: ClientResponse, data: dict):
    if resp.status != 200:
        if data.get("msg") == "用户未登录":
            raise UnauthorizedError(f"认证失败: {data.get('msg')}")
        raise ClientError

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

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


setup_logging()
logger = logging.getLogger(__name__)

