/* SPDX-License-Identifier: GPL-2.0-only */

#include "log.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static ppm_log_level_t g_level = PPM_LOG_INFO;
static int             g_color = -1; /* -1 = auto */

void ppm_log_set_level(ppm_log_level_t level) { g_level = level; }
void ppm_log_set_color(int enabled)           { g_color = enabled; }

static int color_enabled(void) {
    if (g_color != -1) return g_color;
    return isatty(fileno(stderr));
}

static const char *prefix(ppm_log_level_t level, int color) {
    if (color) {
        switch (level) {
        case PPM_LOG_ERROR: return "\033[1;31merror\033[0m: ";
        case PPM_LOG_WARN:  return "\033[1;33mwarn\033[0m: ";
        case PPM_LOG_INFO:  return "\033[1;34minfo\033[0m: ";
        case PPM_LOG_DEBUG: return "\033[1;36mdebug\033[0m: ";
        case PPM_LOG_TRACE: return "\033[2mtrace\033[0m: ";
        }
    } else {
        switch (level) {
        case PPM_LOG_ERROR: return "error: ";
        case PPM_LOG_WARN:  return "warn: ";
        case PPM_LOG_INFO:  return "info: ";
        case PPM_LOG_DEBUG: return "debug: ";
        case PPM_LOG_TRACE: return "trace: ";
        }
    }
    return "";
}

void ppm_log(ppm_log_level_t level, const char *fmt, ...) {
    if (level > g_level) return;

    int color = color_enabled();
    fputs(prefix(level, color), stderr);

    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);

    size_t n = strlen(fmt);
    if (n == 0 || fmt[n - 1] != '\n') fputc('\n', stderr);
}
