#include "device_debug_agent.h"
#include "device_debug_config.h"
#include "browser_open.h"
#include "webrtcpush_run.h"
#include "wifi_config_agent.h"
#include "http_config_mqtt.h"
#include "common.h"

static const char *stream_debug_current_mode(void)
{
    if (webrtcpush_should_use_mpp()) {
        return "c_lang";
    }
    return "webrtc";
}

static int stream_debug_send_json(int sock, const struct sockaddr_in *addr, const char *json)
{
    if (!json || !addr || sock < 0) {
        return -1;
    }
    return sendto(sock, json, strlen(json), 0,
                  (const struct sockaddr *)addr, sizeof(*addr)) >= 0 ? 0 : -1;
}

void stream_debug_handle_mode_query(int sock, const struct sockaddr_in *addr)
{
    cJSON *root = cJSON_CreateObject();
    const char *mode = stream_debug_current_mode();
    char *payload;

    if (!root) {
        return;
    }

    cJSON_AddStringToObject(root, "cmd", "stream_mode_response");
    cJSON_AddStringToObject(root, "mode", mode);

    payload = cJSON_PrintUnformatted(root);
    if (payload) {
        stream_debug_send_json(sock, addr, payload);
        my_zlog_info("推流调试: stream_mode_query -> mode=%s", mode);
        free(payload);
    }
    cJSON_Delete(root);
}

static void stream_debug_send_url_result(int sock, const struct sockaddr_in *addr,
                                         int success, const char *message,
                                         const char *url)
{
    cJSON *root = cJSON_CreateObject();
    char *payload;

    if (!root) {
        return;
    }

    cJSON_AddStringToObject(root, "cmd", "stream_url_result");
    cJSON_AddBoolToObject(root, "success", success ? 1 : 0);
    if (message && message[0]) {
        cJSON_AddStringToObject(root, "message", message);
    }
    if (url && url[0]) {
        cJSON_AddStringToObject(root, "url", url);
    }

    payload = cJSON_PrintUnformatted(root);
    if (payload) {
        stream_debug_send_json(sock, addr, payload);
        free(payload);
    }
    cJSON_Delete(root);
}

void stream_debug_handle_url_update(int sock, const struct sockaddr_in *addr, cJSON *root)
{
    cJSON *url_item = cJSON_GetObjectItemCaseSensitive(root, "url");
    const char *url;
    char effective_url[STREAM_DEBUG_URL_MAX];
    int rc;

    if (strcmp(stream_debug_current_mode(), "webrtc") != 0) {
        stream_debug_send_url_result(sock, addr, 0,
                                   "当前为 C 语言推流，不支持切换网址，请修改设备配置",
                                   NULL);
        my_zlog_warn("推流调试: stream_url_update 拒绝（c_lang 模式）");
        return;
    }

    if (!cJSON_IsString(url_item) || !url_item->valuestring || !url_item->valuestring[0]) {
        stream_debug_send_url_result(sock, addr, 0, "缺少有效的 url 字段", NULL);
        return;
    }

    url = url_item->valuestring;
    my_zlog_info("推流调试: 收到 stream_url_update url=%s", url);

    rc = browser_switch_stream_url(url, effective_url, sizeof(effective_url));
    if (rc == 0) {
        stream_debug_send_url_result(sock, addr, 1, "推流网址已切换", effective_url);
        my_zlog_info("推流调试: 推流网址切换成功 -> %s", effective_url);
    } else {
        stream_debug_send_url_result(sock, addr, 0, "推流网址切换失败", NULL);
        my_zlog_warn("推流调试: 推流网址切换失败");
    }
    wifi_config_agent_rebind_socket();
}

void stream_debug_handle_url_query(int sock, const struct sockaddr_in *addr)
{
    cJSON *root = cJSON_CreateObject();
    char url_buf[STREAM_DEBUG_URL_MAX];
    bool running = false;
    char *payload;

    my_zlog_info("推流调试: 收到 stream_url_query");

    if (!root) {
        return;
    }

    cJSON_AddStringToObject(root, "cmd", "stream_url_response");

    if (strcmp(stream_debug_current_mode(), "webrtc") != 0) {
        cJSON_AddBoolToObject(root, "success", 0);
        cJSON_AddBoolToObject(root, "running", 0);
        cJSON_AddStringToObject(root, "message", "当前为 C 语言推流，不支持查询推流网址");
        my_zlog_warn("推流调试: stream_url_query 拒绝（c_lang 模式）");
    } else {
        url_buf[0] = '\0';
        (void)browser_get_stream_url_info(url_buf, sizeof(url_buf), &running);

        cJSON_AddBoolToObject(root, "success", 1);
        cJSON_AddBoolToObject(root, "running", running ? 1 : 0);
        cJSON_AddStringToObject(root, "url", running ? url_buf : "");
        cJSON_AddStringToObject(root, "message", running ? "当前推流网址" : "浏览器未启动");
        my_zlog_info("推流调试: stream_url_query -> running=%d url=%s",
                     running ? 1 : 0, running ? url_buf : "");
    }

    payload = cJSON_PrintUnformatted(root);
    if (payload) {
        stream_debug_send_json(sock, addr, payload);
        free(payload);
    }
    cJSON_Delete(root);

    wifi_config_agent_rebind_socket();
}
