#include "log.hpp"
#include <chrono>
#include <cstdio>
#include <cstdarg>
#include <ctime>

namespace logc {

static const char* level_label(Level l) {
    switch (l) {
        case Level::Info:    return "\033[36mINFO\033[0m";
        case Level::Success: return "\033[32mOK  \033[0m";
        case Level::Warn:    return "\033[33mWARN\033[0m";
        case Level::Error:   return "\033[31mERROR\033[0m";
    }
    return "????";
}

static FILE* log_stream(Level l) {
    return (l == Level::Warn || l == Level::Error) ? stderr : stdout;
}

void write(Level level, const char* fmt, ...) {
    // ISO-8601 timestamp
    auto now = std::chrono::system_clock::now();
    std::time_t t = std::chrono::system_clock::to_time_t(now);
    std::tm tm_buf{};
    localtime_r(&t, &tm_buf);

    char ts[32];
    std::strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%S", &tm_buf);

    FILE* out = log_stream(level);
    fprintf(out, "\033[90m%s\033[0m %s ", ts, level_label(level));

    va_list args;
    va_start(args, fmt);
    vfprintf(out, fmt, args);
    va_end(args);

    fprintf(out, "\n");
    fflush(out);
}

} // namespace logc
