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

OrderLog g_order_log;

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 OrderLog::open(const std::string& path) {
    ensure_parent_dir(path);
    fp_ = std::fopen(path.c_str(), "a");
}

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

void OrderLog::log_order(const std::string& order_json, const std::string& external_id) {
    std::lock_guard<std::mutex> lock(mutex_);
    sequence_++;

    if (fp_) {
        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::fprintf(fp_, "%s #%d externalId=%s %s\n",
                     ts, sequence_, external_id.c_str(), order_json.c_str());
        std::fflush(fp_);
    }
}
