import os
from datetime import datetime
import logging
from logging.handlers import RotatingFileHandler
import inspect  # 新增导入
from PubLibrary.InifileHelper import IniRead


console_output = IniRead('system', 'console_output', '1')
log_level = IniRead('system', 'algo_log_level', 'INFO')
log_once_cache = set()

# 缓存已经创建过的logger，避免重复创建handler
logger_cache = {}

def init_module_logger(logger_name):
    log_dir = './logs/'
    os.makedirs(log_dir, exist_ok=True)
    log_file = os.path.join(log_dir, f'algo_log_{datetime.now().strftime("%Y-%m-%d")}.log')

    # 已创建直接返回
    if logger_name in logger_cache:
        return logger_cache[logger_name]

    logger = logging.getLogger(logger_name)
    logger.setLevel(log_level)
    if logger.handlers:
        logger_cache[logger_name] = logger
        return logger

    file_handler = RotatingFileHandler(
        log_file,
        maxBytes=10*1024*1024,
        backupCount=10,
        encoding='utf-8'
    )
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    if console_output:
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    logger_cache[logger_name] = logger
    return logger


def algo_log(content, level="INFO", record_once=False):
    # 向上回溯1层栈，拿到调用algo_log的代码文件信息
    frame = inspect.currentframe().f_back
    file_path = frame.f_code.co_filename
    # 提取py文件名（不带后缀/带后缀自选）
    file_name = os.path.basename(file_path)  # 例：zmqServer.py
    # file_name = os.path.splitext(os.path.basename(file_path))[0] # 例：zmqServer

    logger = init_module_logger(file_name)

    if record_once:
        log_key = f"{level.upper()}_{content}"
        if log_key in log_once_cache:
            return
        log_once_cache.add(log_key)

    level_upper = level.upper()
    if level_upper == "DEBUG":
        logger.debug(content)
    elif level_upper == "WARNING":
        logger.warning(content)
    elif level_upper == "ERROR":
        logger.error(content)
    elif level_upper == "FATAL":
        logger.fatal(content)
    else:
        logger.info(content)