"""Logging utilities"""

import json
import logging
from logging.handlers import RotatingFileHandler
from typing import Literal


# 日志 JSON 格式化器
class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        # 复制 record，避免修改原对象
        record_dict = {
            "time": self.formatTime(record, self.datefmt),
            "level": record.levelname,
            "name": record.name,
            "msg": record.getMessage(),
        }
        return json.dumps(record_dict, ensure_ascii=False)


# 日志 普通 格式化器
class NormalFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        return (
            f"[{self.formatTime(record, self.datefmt)}] "
            + f"[{record.levelname}] [{record.name}] {record.getMessage()}"
        )


class Logger:
    def __init__(
        self,
        name: str = __name__,
        log_file_prefix: str = "log",
        max_bytes: int = 10 * 1024 * 1024,
        backup_count: int = 50,
        format: Literal["json", "normal"] = "normal",
    ):
        """
        初始化 Logger

        Args:
            name: logger 名称
            log_file_prefix: 日志文件前缀
            max_bytes: 单个日志文件的最大字节数，默认 10MB
            backup_count: 保留的备份文件数量，默认 50 个
        """
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)

        # 避免重复添加 handler
        if not self.logger.handlers:
            # 控制台输出
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)
            ch.setFormatter(NormalFormatter())

            if format == "json":
                log_file = f"{log_file_prefix}.log.ndjson"
            else:
                log_file = f"{log_file_prefix}.log"

            # 文件输出 - 使用 RotatingFileHandler 实现日志轮转
            fh = RotatingFileHandler(
                log_file,
                maxBytes=max_bytes,
                backupCount=backup_count,
                encoding="utf-8",
            )
            fh.setLevel(logging.DEBUG)
            if format == "normal":
                fh.setFormatter(NormalFormatter())
            elif format == "json":
                fh.setFormatter(JsonFormatter())
            else:
                fh.setFormatter(NormalFormatter())

            self.logger.addHandler(ch)
            self.logger.addHandler(fh)

    def get_logger(self) -> logging.Logger:
        return self.logger

    # 默认只设置 stream handler
    def set_json_fmt(self, all: bool = False) -> None:
        # only set stream handler to json fmt
        for handler in self.logger.handlers:
            if isinstance(handler, logging.StreamHandler) or all:
                handler.setFormatter(JsonFormatter())

    # 默认只设置 stream handler
    def set_norm_fmt(self, all: bool = False) -> None:
        for handler in self.logger.handlers:
            if isinstance(handler, logging.StreamHandler) or all:
                handler.setFormatter(NormalFormatter())


# 全局日志
logger = Logger(
    "LOGIC",
    log_file_prefix="logic",
    format="normal",
).get_logger()
