/**
 * @file hal_log.c
 * @brief HAL 日志实现（JieLi 平台）
 */

#include "hal_log.h"
#include "hal_mutex.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

static const char *level_str[] = {
    [BD_LOG_LEVEL_DEBUG] = "D",
    [BD_LOG_LEVEL_INFO]  = "I",
    [BD_LOG_LEVEL_WARN]  = "W",
    [BD_LOG_LEVEL_ERROR] = "E",
};

/* 日志单行最大长度，超出后截断输出。 */
#define LOG_LINE_MAX  512

static hal_mutex_t s_log_mutex = NULL;

static void log_mutex_init_once(void)
{
    if (!s_log_mutex) {
        s_log_mutex = hal_mutex_create();
    }
}

void hal_log(hal_log_level_t level, const char *tag, const char *fmt, ...)
{
    if (level < BD_LOG_LEVEL_DEBUG || level > BD_LOG_LEVEL_ERROR) {
        return;
    }

    char line[LOG_LINE_MAX];
    int n = snprintf(line, sizeof(line), "[BD][%s][%s] ",
                     level_str[level], tag ? tag : "???");
    if (n < 0) {
        return;
    }
    if ((size_t)n >= sizeof(line)) {
        n = (int)sizeof(line) - 1;
    }

    va_list ap;
    va_start(ap, fmt);
    int m = vsnprintf(line + n, sizeof(line) - n, fmt, ap);
    va_end(ap);

    if (m > 0) {
        n += m;
        if ((size_t)n >= sizeof(line)) {
            n = (int)sizeof(line) - 1;
        }
    }

    /* 追加换行符（保留至少 2 字节给 \n\0）*/
    if ((size_t)n >= sizeof(line) - 1) {
        n = (int)sizeof(line) - 2;
    }
    line[n] = '\n';
    n += 1;
    line[n] = '\0';

    log_mutex_init_once();
    if (s_log_mutex) {
        hal_mutex_lock(s_log_mutex);
    }
    /* 单次输出一行日志 */
    printf("%s", line);
    if (s_log_mutex) {
        hal_mutex_unlock(s_log_mutex);
    }
}
