#include "mqtt_report/get_config.h"

bool load_config(Config &config)
{
    try
    {
        std::string config_path = ament_index_cpp::get_package_share_directory("mqtt_report") + "/config/config.json";

        std::ifstream ifs(config_path);
        if (!ifs.is_open())
        {
            std::cerr << "Failed to open config file: " << config_path << std::endl;
            return false;
        }

        json j;
        ifs >> j;

        config.vid = j.at("vid").get<std::string>();
        config.mqtt_ip = j.at("mqtt").at("ip").get<std::string>();
        config.mqtt_port = j.at("mqtt").at("port").get<int>();

        // 替换 topic 中的 {vid} 为实际 vid 值
        auto replace_vid = [&](const std::string &topic_template)
        {
            std::string topic = topic_template;
            size_t pos = topic.find("{vid}");
            if (pos != std::string::npos)
            {
                topic.replace(pos, 5, config.vid);
            }
            return topic;
        };

        config.info_topic = replace_vid(j.at("mqtt").at("info_topic").get<std::string>());
        config.fault_topic = replace_vid(j.at("mqtt").at("fault_topic").get<std::string>());

        return true;
    }
    catch (const std::exception &e)
    {
        std::cerr << "Error parsing MQTT config: " << e.what() << std::endl;
        return false;
    }
}

std::string generate_mqtt_client_id()
{
    // 获取当前时间戳（以毫秒为单位）
    auto now = std::chrono::system_clock::now();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();

    // 生成一个 4 位随机数
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1000, 9999);
    int random_num = dis(gen);

    // 拼接成 client ID
    std::ostringstream oss;
    oss << "client_" << millis << "_" << std::setw(4) << std::setfill('0') << random_num;

    return oss.str();
}