# log_config.py
import logging
import os
import sys
from pathlib import Path
from logging import Formatter, Filter

class LogColors:
    GREEN = '\033[92m'
    BLUE = '\033[94m'
    RED = '\033[91m'
    YELLOW = '\033[93m'
    RESET = '\033[0m'

class SourceFileFilter(Filter):
    """添加源文件名的过滤器"""
    def filter(self, record):
        record.source_file = os.path.basename(record.pathname) if hasattr(record, 'pathname') else 'unknown'
        return True

class ColoredFormatter(Formatter):
    """带颜色的日志格式化器"""
    def format(self, record):
        message = super().format(record)
        if record.levelno >= logging.ERROR:
            return f"{LogColors.RED}{message}{LogColors.RESET}"
        elif record.levelno >= logging.WARNING:
            return f"{LogColors.YELLOW}{message}{LogColors.RESET}"
        elif record.levelno >= logging.INFO:
            return f"{LogColors.GREEN}{message}{LogColors.RESET}"
        elif record.levelno >= logging.DEBUG:
            return f"{LogColors.BLUE}{message}{LogColors.RESET}"
        return message

def ensure_logs_dir():
    """确保日志目录存在"""
    logs_dir = Path('logs')
    logs_dir.mkdir(parents=True, exist_ok=True)
    return logs_dir

# 初始化日志目录
logs_dir = ensure_logs_dir()

# 日志文件路径
task_log_file = logs_dir / 'task.log'
error_log_file = logs_dir / 'error_task.log'
detail_log_file = logs_dir / 'detail_task.log'

def create_file_handler(filename, level=logging.INFO):
    """创建文件处理器"""
    handler = logging.FileHandler(
        filename=str(filename),
        mode='a',
        encoding='utf-8'
    )
    handler.setLevel(level)
    formatter = logging.Formatter(
        '%(asctime)s - %(source_file)s - %(name)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)
    handler.addFilter(SourceFileFilter())
    return handler

def create_console_handler():
    """创建控制台处理器"""
    handler = logging.StreamHandler()
    formatter = ColoredFormatter(
        '%(asctime)s - %(source_file)s - %(name)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)
    handler.addFilter(SourceFileFilter())
    return handler

def configure_logger(name, level, handlers, propagate=False):
    """配置日志记录器"""
    logger = logging.getLogger(name)
    if not logger.handlers:
        logger.setLevel(level)
        for handler in handlers:
            logger.addHandler(handler)
        logger.propagate = propagate
    return logger

# 配置日志记录器
def configure_task_logger():
    handlers = [
        create_file_handler(task_log_file, logging.INFO),
        create_console_handler()
    ]
    return configure_logger('task_logger', logging.INFO, handlers)

def configure_error_task_logger():
    handlers = [
        create_file_handler(error_log_file, logging.ERROR),
        create_console_handler()
    ]
    return configure_logger('error_task_logger', logging.ERROR, handlers)

def configure_detail_logger():
    handlers = [
        create_file_handler(detail_log_file, logging.DEBUG),
        create_console_handler()
    ]
    return configure_logger('detail_logger', logging.DEBUG, handlers)

# 预配置日志记录器
task_logger = configure_task_logger()
error_logger = configure_error_task_logger()
detail_logger = configure_detail_logger()