import os
import logging
from datetime import datetime


def get_logger(name: str, log_filename: str) -> logging.Logger:
    """
    创建并配置一个每日滚动的日志记录器
    
    Args:
        name: 日志记录器名称
        log_filename: 日志文件名（不含日期和扩展名）
    
    Returns:
        配置好的日志记录器对象
    """
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    
    if logger.handlers:
        return logger
    
    LOG_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "logs")
    os.makedirs(LOG_DIR, exist_ok=True)
    
    class DailyRotatingFileHandler(logging.FileHandler):
        def __init__(self, directory, filename_prefix, encoding=None):
            self.directory = directory
            self.filename_prefix = filename_prefix
            filename = self._get_log_filename()
            super().__init__(filename, encoding=encoding)
        
        def _get_log_filename(self):
            return os.path.join(self.directory, f"{self.filename_prefix}-{datetime.now().strftime('%Y-%m-%d')}.log")
        
        def emit(self, record):
            current_filename = self._get_log_filename()
            if self.baseFilename != current_filename:
                self.close()
                self.baseFilename = current_filename
                self.stream = self._open()
            super().emit(record)
    
    handler = DailyRotatingFileHandler(LOG_DIR, log_filename, encoding="utf-8")
    handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S"))
    
    logger.addHandler(handler)
    
    return logger
