#include "Web_Performance_Log.h"

#include <spdlog/logger.h>
#include <spdlog/sinks/rotating_file_sink.h>

#include <filesystem>
#include <memory>
#include <mutex>
#include <string>

namespace renderive::web {
namespace {

std::mutex log_mutex;
std::shared_ptr<spdlog::logger> performance_logger;
std::filesystem::path performance_log_path;

} // namespace

void initialize_web_performance_log(const std::filesystem::path& log_directory) {
    std::lock_guard lock(log_mutex);
    std::filesystem::create_directories(log_directory);
    performance_log_path = log_directory / "renderive-web-performance.jsonl";
    auto sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
        performance_log_path.string(), 20U * 1024U * 1024U, 5U, false);
    performance_logger = std::make_shared<spdlog::logger>("renderive_web_performance", sink);
    performance_logger->set_pattern("%v");
    performance_logger->set_level(spdlog::level::info);
    performance_logger->flush_on(spdlog::level::info);
}

void write_web_performance_log(std::string_view json_line) noexcept {
    try {
        std::shared_ptr<spdlog::logger> logger;
        {
            std::lock_guard lock(log_mutex);
            logger = performance_logger;
        }
        if (logger)
            logger->info("{}", json_line);
    } catch (...) {
    }
}

std::filesystem::path web_performance_log_path() {
    std::lock_guard lock(log_mutex);
    return performance_log_path;
}

} // namespace renderive::web
