import os
import logging
from colorama import Fore, Style, init
import inspect  # 添加导入用于获取调用堆栈

current_dir = os.path.dirname(os.path.abspath(__file__))
log_path = os.path.join(current_dir, "..", "logs", "ai_swap.log")

# 初始化 colorama
init(autoreset=True)

class ColoredFormatter(logging.Formatter):
    COLORS = {
        'DEBUG': Fore.CYAN,
        'INFO': Fore.GREEN,
        'WARNING': Fore.YELLOW,
        'ERROR': Fore.RED,
        'CRITICAL': Fore.RED + Style.BRIGHT,
    }

    def format(self, record):
        levelname = record.levelname
        # 添加文件名和行号到日志记录
        record.filename = os.path.basename(record.pathname)  # 仅显示文件名
        record.location = f"{record.filename}:{record.lineno}"
        
        if levelname in self.COLORS:
            color = self.COLORS[levelname]
            record.levelname = f"{color}{levelname}{Style.RESET_ALL}"
            record.msg = f"{color}{record.msg}{Style.RESET_ALL}"
        return super().format(record)

def setup_logger(name):
    # 配置日志
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    # 创建文件处理器
    file_handler = logging.FileHandler(log_path, encoding='utf-8') 
    file_handler.setLevel(logging.DEBUG) 

    # 创建格式化器 - 添加详细位置信息 [文件名:行号]
    console_formatter = ColoredFormatter(
        '%(asctime)s - %(levelname)s - [%(location)s] %(funcName)s() - %(message)s'
    )
    
    # 文件处理器使用非彩色格式
    file_formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] %(funcName)s() - %(message)s'
    )

    console_handler.setFormatter(console_formatter)
    file_handler.setFormatter(file_formatter)

    # 将处理器添加到日志记录器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    return logger