/**
 * @file logger.h
 * @brief 简易日志系统
 */

#ifndef LOGGER_H
#define LOGGER_H

#include <cstdio>
#include <ctime>
#include <cstdarg>

enum LogLevel {
    LOG_LEVEL_DEBUG = 0,
    LOG_LEVEL_INFO  = 1,
    LOG_LEVEL_WARN  = 2,
    LOG_LEVEL_ERROR = 3
};

class Logger {
public:
    static void init(LogLevel level) {
        s_log_level = level;
    }
    
    static void log(LogLevel level, const char* file, int line, const char* fmt, ...) {
        if (level < s_log_level) return;
        
        // 时间戳
        time_t now = time(nullptr);
        struct tm* t = localtime(&now);
        char timestamp[32];
        strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", t);
        
        // 日志级别
        const char* level_str[] = {"DEBUG", "INFO", "WARN", "ERROR"};
        
        // 输出前缀
        fprintf(stderr, "[%s] [%s] ", timestamp, level_str[level]);
        
        // 输出消息
        va_list args;
        va_start(args, fmt);
        vfprintf(stderr, fmt, args);
        va_end(args);
        
        fprintf(stderr, " (%s:%d)\n", file, line);
        fflush(stderr);
    }

private:
    static LogLevel s_log_level;
};

// 宏定义
#define LOG_DEBUG(fmt, ...) Logger::log(LOG_LEVEL_DEBUG, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_INFO(fmt, ...)  Logger::log(LOG_LEVEL_INFO,  __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...)  Logger::log(LOG_LEVEL_WARN,  __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) Logger::log(LOG_LEVEL_ERROR, __FILE__, __LINE__, fmt, ##__VA_ARGS__)

#endif // LOGGER_H
