"""财务报销自动化工具包"""

import io
import logging
import sys
from pathlib import Path

_LOG_FMT = "%(asctime)s [%(levelname)-5s] %(name)s: %(message)s"
_LOG_DATE_FMT = "%Y-%m-%d %H:%M:%S"
_LOG_FILE = Path(__file__).resolve().parent.parent / "pipeline.log"


def get_logger(name: str) -> logging.Logger:
    """获取带时间戳的日志记录器

    输出格式: 2026-05-24 12:34:56 [INFO ] extractor: 扫描目录: ...
    日志同时输出到终端和项目根目录的 pipeline.log
    """
    logger = logging.getLogger(name)
    if not logger.handlers:
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter(_LOG_FMT, _LOG_DATE_FMT)

        # 终端输出
        utf8_stream = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
        stream_handler = logging.StreamHandler(utf8_stream)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)

        # 文件输出
        file_handler = logging.FileHandler(str(_LOG_FILE), encoding="utf-8")
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    return logger