#include "request_log.hpp"
#include "log.hpp"
#include <chrono>
#include <ctime>
#include <sys/stat.h>

static void ensure_parent_dir(const std::string& path) {
    size_t pos = path.rfind('/');
    if (pos != std::string::npos) {
        mkdir(path.substr(0, pos).c_str(), 0755);
    }
}

void RequestLog::open(const std::string& path) {
    ensure_parent_dir(path);
    fp_ = std::fopen(path.c_str(), "a");
    if (!fp_) logc::warn("cannot open request log: %s", path.c_str());
}

void RequestLog::close() {
    if (fp_) { std::fclose(fp_); fp_ = nullptr; }
}

void RequestLog::log(const std::string& remote, const std::string& method,
                     const std::string& url, int status, int duration_ms,
                     const std::string& response) {
    if (!fp_) return;
    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);

    std::lock_guard<std::mutex> lock(mutex_);
    std::fprintf(fp_, "%s %s %s %s %d %dms %s\n",
                 ts, remote.c_str(), method.c_str(), url.c_str(),
                 status, duration_ms, response.c_str());
    std::fflush(fp_);
}
