#include "logger.hpp"
#include <iomanip>

std::ofstream Logger::log_file;

void Logger::set_log_to_file(const std::string &filename)
{
    log_file.open(filename, std::ios::app);
    if (!log_file.is_open())
    {
        std::cerr << "[Logger] Failed to open log file: " << filename << std::endl;
    }
}

std::string Logger::get_time_string()
{
    std::time_t now = std::time(nullptr);
    std::tm *ltm = std::localtime(&now);
    char buf[32];
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", ltm);
    return std::string(buf);
}

void Logger::log(LogLevel level, const std::string &msg)
{
    std::string level_str;
    switch (level)
    {
    case LogLevel::INFO:
        level_str = "[INFO] ";
        break;
    case LogLevel::WARN:
        level_str = "[WARN] ";
        break;
    case LogLevel::ERROR:
        level_str = "[ERROR]";
        break;
    }

    std::string full_msg = get_time_string() + " " + level_str + " " + msg;

    std::cout << full_msg << std::endl;

    if (log_file.is_open())
    {
        log_file << full_msg << std::endl;
    }
}
