#include "device_identity.h"
#include "http_config_mqtt.h"
#include "common.h"
#include "http_request.h"
#include "wifi_autoconfig.h"
#include <strings.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';
}

// 联调前可临时改为 "EN" 强制英语；正式环境留空，走接口 moreInfo.language
#ifndef DEVICE_LANGUAGE_MOCK
#define DEVICE_LANGUAGE_MOCK ""
#endif

static void apply_region_language_code(const char *region) {
    if (region == NULL || region[0] == '\0') {
        audio_set_language(AUDIO_LANG_ZH);
        my_zlog_debug("区域语言未指定，默认中文");
        return;
    }
    if (strcasecmp(region, "CN") == 0 || strcasecmp(region, "ZH") == 0 ||
        strcasecmp(region, "zh") == 0) {
        audio_set_language(AUDIO_LANG_ZH);
        my_zlog_info("区域语言: 中文 (CN)");
        return;
    }
    if (strcasecmp(region, "EN") == 0 || strcasecmp(region, "en") == 0) {
        audio_set_language(AUDIO_LANG_EN);
        my_zlog_info("区域语言: 英语 (EN)");
        return;
    }
    my_zlog_warn("未知区域语言: %s，默认中文", region);
    audio_set_language(AUDIO_LANG_ZH);
}

static void parse_moreinfo_language(cJSON *data) {
    const char *mock = DEVICE_LANGUAGE_MOCK;
    if (mock[0] != '\0') {
        my_zlog_info("使用联调假字段 DEVICE_LANGUAGE_MOCK=%s", mock);
        apply_region_language_code(mock);
        return;
    }

    if (!data) {
        apply_region_language_code("CN");
        return;
    }

    cJSON *moreInfo = cJSON_GetObjectItemCaseSensitive(data, "moreInfo");
    if (!moreInfo) {
        my_zlog_debug("moreInfo 缺失，默认中文");
        apply_region_language_code("CN");
        return;
    }

    cJSON *language = cJSON_GetObjectItemCaseSensitive(moreInfo, "language");
    if (!cJSON_IsString(language) || language->valuestring == NULL || language->valuestring[0] == '\0') {
        my_zlog_debug("moreInfo.language 缺失，默认中文");
        apply_region_language_code("CN");
        return;
    }

    apply_region_language_code(language->valuestring);
}

static int fetch_device_config_json(struct MemoryStruct *chunk) {
    CURL *curl;
    CURLcode res;

    chunk->memory = malloc(1);
    chunk->size = 0;
    if (!chunk->memory) {
        return -1;
    }

    curl = curl_easy_init();
    if (!curl) {
        free(chunk->memory);
        chunk->memory = NULL;
        return -1;
    }

    char url[512];
    snprintf(url, sizeof(url), "https://fcrs-api.yd-ss.com/device/getConfig?deviceNo=%s",
             mqtt_topic_pure_number());
    my_zlog_debug("getConfig 拉取区域语言: %s", url);

    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");
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 8L);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
        my_zlog_warn("getConfig 请求失败: %s", curl_easy_strerror(res));
        free(chunk->memory);
        chunk->memory = NULL;
        chunk->size = 0;
        return -1;
    }
    return 0;
}

int device_fetch_region_language(void) {
    struct MemoryStruct chunk = {NULL, 0};
    int rc = -1;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    if (fetch_device_config_json(&chunk) != 0) {
        curl_global_cleanup();
        return -1;
    }

    cJSON *root = cJSON_Parse(chunk.memory);
    if (!root) {
        my_zlog_warn("getConfig JSON 解析失败");
        goto cleanup;
    }

    cJSON *code = cJSON_GetObjectItemCaseSensitive(root, "code");
    if (!cJSON_IsNumber(code) || code->valueint != 200) {
        my_zlog_warn("getConfig 返回码异常");
        cJSON_Delete(root);
        goto cleanup;
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(root, "data");
    parse_moreinfo_language(data);
    cJSON_Delete(root);
    rc = 0;

cleanup:
    free(chunk.memory);
    curl_global_cleanup();
    return rc;
}

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_debug("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_debug("  [%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';
        }

        parse_moreinfo_language(data);
    }

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

// 拉取并解析 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_debug("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_debug("http_mqtt_video_init reconnect");
        }
    }
    my_zlog_error("http_mqtt_video_init failure");
    return -1;
}