#include "mqtt_client_wrapper.hpp"

std::shared_ptr<MQTTClient> mqtt_client;
std::atomic<bool> mqtt_restart_required{false};

static uint16_t broadcast_sequence = 0;
void send_broadcast_message_with_seq(const std::string &msg, uint16_t seq);

// MQTT 回调定义
static void on_mqtt_connected()
{
    LOG_INFO("[MQTT] Connected to broker.");
    mqtt_client->subscribe(g_mqtt_config.topics.downlink);
}

static void on_mqtt_disconnected()
{
    LOG_WARN("[MQTT] Disconnected from broker.");
}

static void on_mqtt_message_received(const std::string &topic, const std::string &message)
{
    LOG_INFO("[MQTT] Received message on topic [" + topic + "], len = " + std::to_string(message.size()));

    try
    {
        // 1. 解析 JSON 并转成紧凑格式
        nlohmann::json j = nlohmann::json::parse(message);
        std::string compact_str = j.dump(); // 紧凑格式（无空格和缩进）

        std::vector<uint8_t> data_unit;

        // 2. 参数设置时间（6字节）
        std::time_t t = std::time(nullptr);
        std::tm *now = std::localtime(&t);
        data_unit.push_back(static_cast<uint8_t>(now->tm_year % 100)); // 年
        data_unit.push_back(static_cast<uint8_t>(now->tm_mon + 1));    // 月
        data_unit.push_back(static_cast<uint8_t>(now->tm_mday));       // 日
        data_unit.push_back(static_cast<uint8_t>(now->tm_hour));       // 时
        data_unit.push_back(static_cast<uint8_t>(now->tm_min));        // 分
        data_unit.push_back(static_cast<uint8_t>(now->tm_sec));        // 秒

        // 3. 流水号（2字节，递增）
        uint16_t seq = broadcast_sequence++ % 65524;
        data_unit.push_back((seq >> 8) & 0xFF);
        data_unit.push_back(seq & 0xFF);

        // 4. JSON长度（2字节，大端）
        uint16_t json_len = static_cast<uint16_t>(compact_str.size());
        data_unit.push_back((json_len >> 8) & 0xFF);
        data_unit.push_back(json_len & 0xFF);

        // 5. JSON内容
        data_unit.insert(data_unit.end(), compact_str.begin(), compact_str.end());

        // 6. 构造 FullPacket
        FullPacket pkt;
        pkt.command_id = 0xD5;
        pkt.response_flag = 0xFE;
        pkt.vin = g_mqtt_config.vin;
        pkt.encryption_method = 0x01;
        pkt.data_length = data_unit.size();
        pkt.data_unit = std::move(data_unit);

        // 7. 编码打包
        std::vector<uint8_t> raw = ProtocolCodec::encode_full_packet(pkt);
        std::string str_msg(reinterpret_cast<const char *>(raw.data()), raw.size());

        send_broadcast_message_with_seq(str_msg, seq);
    }
    catch (const std::exception &e)
    {
        LOG_ERROR(std::string("[MQTT] Failed to process incoming JSON: ") + e.what());
    }
}

void mqtt_client_thread_func()
{
    while (true)
    {
        const auto &cfg = g_mqtt_config;
        mqtt_client = std::make_unique<MQTTClient>(cfg);
        mqtt_client->setConnectCallback(on_mqtt_connected);
        mqtt_client->setDisconnectCallback(on_mqtt_disconnected);
        mqtt_client->setMessageCallback(on_mqtt_message_received);

        mqtt_client->connect();

        // 主线程监听重启信号
        while (!mqtt_restart_required)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        // 需要重启
        LOG_INFO("[MQTT] Restarting client...");
        mqtt_client->disconnect(); // 可加锁
        mqtt_client.reset();
        mqtt_restart_required = false;
    }
}
