from app.settings import settings
import logging
import logging.handlers
from pathlib import Path

class Loggin:
    def __init__(self) -> None:
        debug = settings.DEBUG
        if debug:
            self.level = "DEBUG"
        else:
            self.level = "INFO"
    
    def setup_logger(self):
        """根据settings配置设置日志系统，控制台输出支持颜色"""
        # 获取日志配置
        log_level = self.level
        log_format = settings.LOG_FORMAT
        
        # 获取文件日志配置
        file_logging_enabled = True
        log_file_path = ''
        
        # 创建日志目录
        if file_logging_enabled:
            log_file_path = Path(settings.LOGS_ROOT) / "app.log"
            log_file_path.parent.mkdir(exist_ok=True, parents=True)
        
        # 构建处理器列表
        handlers = []
        
        # 控制台处理器（支持彩色输出）
        console_enabled = self.level == "DEBUG"
        if console_enabled:
            print('添加控制台日志打印')
            import colorlog  # 新增：导入colorlog库

            # 定义彩色日志级别对应的颜色
            log_colors = {
                'DEBUG': 'white',
                'INFO': 'green',
                'WARNING': 'yellow',
                'ERROR': 'red',
                'CRITICAL': 'bold_red',
            }
            
            # 创建彩色格式化器
            console_formatter = colorlog.ColoredFormatter(
                # 彩色格式中需要使用%(log_color)s作为颜色标记
                "%(log_color)s" + log_format,
                datefmt=settings.DATETIME_FORMAT,
                log_colors=log_colors,
                reset=True,
                style='%'
            )
            
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(console_formatter)
            handlers.append(console_handler)
        
        # 文件处理器（如果启用）
        if file_logging_enabled:
            # 获取文件大小限制和备份数量
            max_bytes = settings.LOG_FILE_MAX_SIZE
            backup_count = settings.LOG_FILE_BACKUP_COUNT
            
            # 文件日志使用普通格式化器（不添加颜色代码）
            file_formatter = logging.Formatter(
                log_format,
                datefmt=settings.DATETIME_FORMAT
            )
            
            file_handler = logging.handlers.RotatingFileHandler(
                log_file_path,
                maxBytes=max_bytes,
                backupCount=backup_count,
                encoding='utf-8'
            )
            file_handler.setFormatter(file_formatter)
            handlers.append(file_handler)
        
        # 配置根日志记录器
        logging.basicConfig(
            level=getattr(logging, log_level.upper(), logging.INFO),
            format=log_format,
            handlers=handlers,
            datefmt=settings.DATETIME_FORMAT
        )
        
        # 设置第三方库的日志级别，减少噪音
        logging.getLogger("urllib3").setLevel(logging.WARNING)
        logging.getLogger("selenium").setLevel(logging.WARNING)
        logging.getLogger("playwright").setLevel(logging.WARNING)
        logging.getLogger("tortoise").setLevel(logging.WARNING)
        logging.getLogger("httpcore").setLevel(logging.WARNING)
        
        # 记录日志系统初始化
        logger = logging.getLogger(__name__)
        logger.info(f"Logging configured - Level: {log_level}, File: {log_file_path if file_logging_enabled else 'Disabled'}")
        return logger



loggin = Loggin()
logger = loggin.setup_logger()
