#include "device_identity.h"
#include "http_config_mqtt.h"
#include "common.h"
#include "http_request.h"

static DEVICE_MQTTCONFIG s_mqtt_cam_config;
DEVICE_MQTTCONFIG *g_mqtt_cam_config_t = &s_mqtt_cam_config; 

/*使用默认的mqtt服务器地址和WEBRTC的信令服务器*/
void default_device_mqtt_cam(){
    strncpy(g_mqtt_cam_config_t->mqtt_servers[0], DEFAULT_MQTT_BROKER_ADDRESS , sizeof(g_mqtt_cam_config_t->mqtt_servers[0]) - 1);
    g_mqtt_cam_config_t->mqtt_servers[0][sizeof(g_mqtt_cam_config_t->mqtt_servers[0]) - 1] = '\0'; 
    g_mqtt_cam_config_t->mqtt_count =1;

    strncpy(g_mqtt_cam_config_t->videourl, DEVICE_DEFAULT_VIDEO , sizeof(g_mqtt_cam_config_t->videourl) - 1);
    g_mqtt_cam_config_t->videourl[sizeof(g_mqtt_cam_config_t->videourl) - 1] = '\0';
}

int parse_device_config(const char *json_str) {
    // 解析 JSON
    cJSON *root = cJSON_Parse(json_str);
    if (!root) {
        fprintf(stderr, "JSON 解析失败: %s\n", cJSON_GetErrorPtr());
        return -1;
    }

    // 1. 提取顶层字段
    cJSON *message = cJSON_GetObjectItemCaseSensitive(root, "message");
    cJSON *code = cJSON_GetObjectItemCaseSensitive(root, "code");
    
    if (cJSON_IsString(message) && cJSON_IsNumber(code)) {
        my_zlog_debug("状态: %s", message->valuestring);
        my_zlog_debug("状态码: %d", code->valueint);
        if(code->valueint!=200){
            my_zlog_error("code error");

            default_device_mqtt_cam();

            return -1;
        }
    }

    // 2. 提取 data 对象
    cJSON *data = cJSON_GetObjectItemCaseSensitive(root, "data");
    if (data) {
        // 3. 提取 mqtt 服务器列表
        cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(data, "mqtt");
        if (cJSON_IsArray(mqtt)) {
            my_zlog_info("MQTT 服务器:");
            cJSON *item;
            int i = 0;
            cJSON_ArrayForEach(item, mqtt) {
                if (cJSON_IsString(item)) {
                    strncpy(g_mqtt_cam_config_t->mqtt_servers[i], item->valuestring, sizeof(g_mqtt_cam_config_t->mqtt_servers[i]) - 1);
                    g_mqtt_cam_config_t->mqtt_servers[i][sizeof(g_mqtt_cam_config_t->mqtt_servers[i]) - 1] = '\0'; 
                    my_zlog_info("  [%d] %s", i+1, g_mqtt_cam_config_t->mqtt_servers[i]);   
                    i = i + 1; 
                }
            }
            g_mqtt_cam_config_t->mqtt_count = i;
        }

        // 4. 提取 api 和 videoUrl
        cJSON *videoUrl = cJSON_GetObjectItemCaseSensitive(data, "videoUrlForDevice");
        
        if (cJSON_IsString(videoUrl)) {
            my_zlog_debug("视频地址: %s", videoUrl->valuestring);
           strncpy(g_mqtt_cam_config_t->videourl, videoUrl->valuestring, sizeof(g_mqtt_cam_config_t->videourl) - 1);
            g_mqtt_cam_config_t->videourl[sizeof(g_mqtt_cam_config_t->videourl) - 1] = '\0';
        }
    }

    // 释放内存
    cJSON_Delete(root);
}

// 拉取并解析 JSON 数据的函数
int deviceconfig_mqtt_video_init() {
    CURL *curl;
    CURLcode res;
    struct MemoryStruct chunk = {NULL, 0};

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (!curl) {
        fprintf(stderr, "Failed to initialize CURL\n");
        my_zlog_error("Failed to initialize CURL");

        default_device_mqtt_cam();

        return -1;
    }

    // 构造请求 URL
    char url[512];
    snprintf(url, sizeof(url), "https://fcrs-api.yd-ss.com/device/getConfig?deviceNo=%s", mqtt_topic_pure_number());
    my_zlog_info("url:%s",url);

    // 设置 CURL 选项
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writememorycallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

    // 执行 HTTP 请求
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        my_zlog_error("curl_easy_perform() failed");

        default_device_mqtt_cam();

        return -1;
    } else {
        // 解析返回的 JSON 数据
        cJSON *root = cJSON_Parse(chunk.memory);
        if (!root) {
            fprintf(stderr, "JSON parse error: %s\n", cJSON_GetErrorPtr());
            my_zlog_error("JSON parse error");
        } else {
            parse_device_config(chunk.memory);
        }
    }

    // 清理资源
    free(chunk.memory);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}

/*mqtt服务器和视频流地址初始化*/
int http_mqtt_video_init(){
    for(int i =0; i<3;i++){
        if(deviceconfig_mqtt_video_init()==0){
            my_zlog_info("http_mqtt_video_init success");
            return 0;
        }else {
            my_zlog_info("http_mqtt_video_init reconnect");
        }
    }
    my_zlog_error("http_mqtt_video_init failure");
    return -1;
}