const winston = require("winston");
const { logsDir } = require("./unit");

const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  debug: 4,
};

const level = () => {
  return "info"; // 显示信息级别日志
};

const colors = {
  error: "red",
  warn: "yellow",
  info: "green",
  http: "magenta",
  debug: "white",
};

winston.addColors(colors);

// 使用过滤转换器来过滤日志
const filterLogs = winston.format((info, opts) => {
  // 定义要显示的关键字
  const allowedKeywords = [
    "系统启动完成", "故障", "报警", "禁用", "错误", "AD 错误", "启动", 
    "连接", "登录", "摄像头", "麦克风", "音频", "编码器", "服务", "模块错误"
  ];
  
  // 检查是否是错误或警告级别，或者包含关键字
  const shouldDisplay = info.level === "error" || 
                       info.level === "warn" ||
                       allowedKeywords.some(keyword => info.message.includes(keyword));
  
  // 如果符合条件则返回info对象，否则返回false以过滤掉
  return shouldDisplay ? info : false;
});

const format = winston.format.combine(
  filterLogs(), // 应用过滤器
  winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:SSS" }),
  winston.format.colorize({ all: true }), // 为所有日志着色
  winston.format.printf(info => {
    return `${info.timestamp} ${info.level}: ${info.message}`;
  })
);

const transports = [
  new winston.transports.Console(), // 添加控制台输出
  new winston.transports.File({
    filename: "logs/error.log",
    level: "error",
    format: winston.format.combine(
      winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
      winston.format.errors({ stack: true }),
      winston.format.splat(),
      winston.format.json()
    ),
  }),
  new winston.transports.File({ 
    filename: "logs/all.log", 
    format: winston.format.combine(
      winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
      winston.format.printf(info => {
        const allowedKeywords = [
          "系统启动完成", "故障", "报警", "禁用", "错误", "AD 错误", "启动", 
          "连接", "登录", "摄像头", "麦克风", "音频", "编码器", "服务", "模块错误"
        ];
        
        const shouldDisplay = info.level === "error" || 
                             info.level === "warn" ||
                             allowedKeywords.some(keyword => info.message.includes(keyword));
        
        return shouldDisplay ? `${info.timestamp} ${info.level}: ${info.message}` : '';
      })
    )
  }),
];

global.logger = winston.createLogger({
  level: level(),
  levels,
  format,
  transports,
});

module.exports = global.logger;