
#include "os/os_api.h"
#include "system/timer.h"
#include "http/http_cli.h"
#include "json_c/json_tokener.h"
#include "baidu_chat_agents_engine.h"
#include "sa_audio.h"
#include "app_config.h"
#include "cJSON.h"

#define BRTC_APP_ID "xxxx"    //请填写你们申请的appId, 申请路径：https://cloud.baidu.com/doc/RTC/index.html

// 定义基础URL和各个端点
//#define GENERATE_AI_AGENT_BASE_URL      "http://rtc-aiagent.baidubce.com/api/v1/aiagent"
//#define GENERATE_AI_AGENT_BASE_URL      "http://ai.agent.kaywang.cn:8988/api/v1/aiagent"
//#define GENERATE_AI_AGENT_BASE_URL      "http://ai.agent.kaywang.cn:8988/test/v1/aiagent"
//需要客户自己搭建服务，服务端的参考代码
//https://cloud.baidu.com/doc/RTC/s/wm8y592lc下载userserver-and-web-demo.zip
//下面GENERATE_AI_AGENT_BASE_URL的地址为172.18.103.132换成客户搭建服务的ip或者域名
#define GENERATE_AI_AGENT_BASE_URL      "http://172.18.100.227:8936/api/v1/aiagent"
#define GENERATE_AI_AGENT_CALL_ENDPOINT "/generateAIAgentCall"
#define STOP_AI_AGENT_CALL_ENDPOINT     "/stopAIAgentInstance"
//
// 完整的URL宏
#define GENERATE_AI_AGENT_CALL_URL      GENERATE_AI_AGENT_BASE_URL GENERATE_AI_AGENT_CALL_ENDPOINT
#define STOP_AI_AGENT_CALL_URL          GENERATE_AI_AGENT_BASE_URL STOP_AI_AGENT_CALL_ENDPOINT

#ifdef BRTC_VAD_CLOSE_ENABLE
#define ASR_LONG_AUDIO_MODE "true"
#else
#define ASR_LONG_AUDIO_MODE "false"
#endif

//app_id需要申请的值
#ifdef BRTC_ENABLE_G722
#define GENERATE_AI_AGENT_CALL_DATA "{ \"app_id\": \"xxxx\", \
\"config\" : \"{\\\"llm\\\" : \\\"LLMRacing\\\", \\\"llm_token\\\" : \\\"no\\\", \
\\\"rtc_ac\\\": \\\"g722\\\", \\\"lang\\\" : \\\"zh\\\", \\\"asr_long_audio_mode\\\" : " ASR_LONG_AUDIO_MODE "}\", \
\"quick_start\": true}"
#else
#define GENERATE_AI_AGENT_CALL_DATA "{ \"app_id\": \"xxxx\", \
\"config\" : \"{\\\"llm\\\" : \\\"LLMRacing\\\", \\\"llm_token\\\" : \\\"no\\\", \
\\\"rtc_ac\\\": \\\"pcmu\\\", \\\"lang\\\" : \\\"zh\\\", \\\"asr_long_audio_mode\\\" : " ASR_LONG_AUDIO_MODE "}\", \
\"quick_start\": true}"
#endif

static bool g_agent_need_recover = false;

static u32 time_mute_play_mp3 = 0;
bool       time_mute_play_mp3_valid = true;

static BaiduChatAgentEngine *g_engine = NULL;
static u32 time_last_asr = 0;

static int time_task_pid = 0;
static int brtc_agent_task_pid = 0;
static int kill_time_task_req = 0;
static int kill_brtc_agent_task_req = 0;

static bool g_brtc_agent_normal_quit = false;   //正常退出
static bool g_brtc_agent_abnormal_quit = false; //异常退出
static bool g_brtc_agent_abnormal_quit_first = true; //异常退出会多次事件，只监控第一次
static bool g_net_status_conneted_failed = false;      //网络状态
static bool g_brtc_agent_exit_quickly = false;
static bool g_brtc_agent_can_exit = false;              //正常运行中
static bool g_brtc_license_abnormal_exit = false;    //true:表示鉴权失败退出

static bool g_brtc_speaking_tts     = false;         //tts是否播放中
static bool g_brtc_delay_play_mp3   = false;         // 延迟播放音乐开关打开
static char g_brtc_playurl[1024];
char* g_json_str = NULL;

#define DEFAULT_BUFFER_SIZE (4 * 1024)
#define DEFAULT_TIMEOUT_MS 5000
// HTTP响应结构体
typedef struct {
    char *data;          // 响应数据
    int data_len;        // 数据长度
    int status_code;     // HTTP状态码
    bool success;        // 请求是否成功
} http_response_t;

// HTTP请求类型
typedef enum {
    HTTP_GET,
    HTTP_POST,
    HTTP_PUT
} http_method_t;

// HTTP请求参数
typedef struct {
    const char *url;              // 请求URL
    http_method_t method;         // 请求方法
    const char *post_data;        // POST数据（仅POST/PUT时使用）
    const char *content_type;     // Content-Type（仅POST/PUT时使用）
    int timeout_ms;               // 超时时间（毫秒）
    const char *custom_headers;   // 自定义HTTP头（可选）
} http_request_params_t;

http_response_t* send_http_request(const http_request_params_t *params) {
    if (!params || !params->url) {
        printf("Invalid parameters\n");
        return NULL;
    }

    int ret = 0;
    http_body_obj http_body_buf;
    httpcli_ctx* ctx = NULL;
    http_response_t* response = NULL;

    // 分配响应结构体
    response = (http_response_t*)calloc(1, sizeof(http_response_t));
    if (!response) {
        printf("Failed to allocate response\n");
        return NULL;
    }

    // 分配HTTP客户端上下文
    ctx = (httpcli_ctx*)calloc(1, sizeof(httpcli_ctx));
    if (!ctx) {
        printf("Failed to allocate http context\n");
        free(response);
        return NULL;
    }

    // 初始化HTTP body缓冲区
    memset(&http_body_buf, 0x0, sizeof(http_body_obj));
    http_body_buf.recv_len = 0;
    http_body_buf.buf_len = DEFAULT_BUFFER_SIZE;
    http_body_buf.buf_count = 1;
    http_body_buf.p = (char*)malloc(http_body_buf.buf_len * http_body_buf.buf_count);

    if (!http_body_buf.p) {
        printf("Failed to allocate buffer\n");
        free(ctx);
        free(response);
        return NULL;
    }

    // 设置HTTP请求参数
    ctx->url = params->url;
    ctx->timeout_millsec = params->timeout_ms > 0 ? params->timeout_ms : DEFAULT_TIMEOUT_MS;
    ctx->priv = &http_body_buf;
    ctx->connection = "close";

    // 设置自定义头部（如果有）
    if (params->custom_headers) {
        ctx->user_http_header = params->custom_headers;
    }

    // 根据请求类型执行相应的HTTP方法
    switch (params->method) {
        case HTTP_POST:
            if (params->post_data && params->content_type) {
                ctx->data_format = params->content_type;
                ctx->post_data = params->post_data;
                ctx->data_len = strlen(params->post_data);
                ret = httpcli_post(ctx);
            } else {
                printf("POST request requires data and content type\n");
                ret = -1;
            }
            break;

        case HTTP_GET:
            ret = httpcli_get(ctx);
            break;

        default:
            printf("Unsupported HTTP method\n");
            ret = -1;
            break;
    }

    // 处理响应
    if (ret == HERROR_OK) {
        response->success = true;
        response->status_code = 200; // 这里可能需要从ctx获取实际的状态码

        if (http_body_buf.recv_len > 0) {
            response->data_len = http_body_buf.recv_len;
            response->data = (char*)malloc(http_body_buf.recv_len + 1);
            if (response->data) {
                memcpy(response->data, http_body_buf.p, http_body_buf.recv_len);
                response->data[http_body_buf.recv_len] = '\0';
            }
        }
    } else {
        response->success = false;
        response->status_code = 0;
    }

    // 清理资源
    httpcli_close(ctx);

    if (http_body_buf.p) {
        free(http_body_buf.p);
    }

    if (ctx) {
        free(ctx);
    }

    return response;
}

void free_http_response(http_response_t *response) {
    if (response) {
        if (response->data) {
            free(response->data);
        }
        free(response);
    }
}

void http_post_request(const char* url, const char* json_data) {
    http_request_params_t params = {
        .url = url,
        .method = HTTP_POST,
        .post_data = json_data,
        .content_type = "application/json",
        .timeout_ms = 5000
    };

    http_response_t* response = send_http_request(&params);
    if (response && response->success) {
        printf("Response: %s\n", response->data);
    }
    free_http_response(response);
}

int extract_value_by_key(const char *input, const char *key, char *output, size_t output_size) {
    cJSON *json = cJSON_Parse(input);
    if (json == NULL) {
        return -1;
    }

    cJSON *item = cJSON_GetObjectItem(json, key);
    if (item == NULL) {
        cJSON_Delete(json);
        return -1;
    }

    // 直接获取值的字符串表示
    if (cJSON_IsNumber(item)) {
        snprintf(output, output_size, "%.0f", item->valuedouble);
    } else if (cJSON_IsString(item)) {
        snprintf(output, output_size, "%s", item->valuestring);
    } else if (cJSON_IsBool(item)) {
        snprintf(output, output_size, "%s", cJSON_IsTrue(item) ? "true" : "false");
    } else {
        // 对于其他类型，获取其 JSON 字符串表示
        char *item_string = cJSON_Print(item);
        if (item_string) {
            snprintf(output, output_size, "%s", item_string);
            free(item_string);
        } else {
            cJSON_Delete(json);
            return -1;
        }
    }

    cJSON_Delete(json);
    return 0;
}

void stopAIAgent(const char *g_json_str) {
    const char *key = "ai_agent_instance_id";
    char output[64]; // 输出缓冲区
    char stop_agent_post_data[128];

    // 调用提取函数
    if (extract_value_by_key(g_json_str, key, output, sizeof(output)) == 0) {
        printf("Extracted value for key '%s': %s\n", key, output);
        snprintf(stop_agent_post_data, sizeof(stop_agent_post_data),
                 "{\"app_id\":\"%s\",\"ai_agent_instance_id\":\"%s\"}",
                 BRTC_APP_ID, output);
        http_post_request(STOP_AI_AGENT_CALL_URL, stop_agent_post_data);
    } else {
        printf("Failed to extract value for key '%s'\n", key);
    }
}

//音频模块 独占使用  brtc优先级> MP3播放
bool audio_device_multi_used = false;

void brtc_audio_device_need_used_set(bool need_used){
    audio_device_multi_used = need_used;
}

bool brtc_audio_device_need_used_get(){
    return  audio_device_multi_used;
}

extern int mp3_set_dec_volume_reset();
extern int mp3_set_dec_volume_mute(int volume);

extern int sa_net_music_audio_play_pause(bool pause);
extern int app_sdk_audio_play_pause(bool);

bool brtc_aiagent_tts_busy() {
    return  g_brtc_speaking_tts;
}
void onAIAgentSpeaking(bool speaking) {  //rtc tts回调是否有回话。
    g_brtc_speaking_tts = speaking;

    printf("SSSSSSSSSSSSSSSSSSSSSSSSSpeaking status:%d, audio_device_multi_used:%d", speaking, audio_device_multi_used);
    if (speaking) {
        //如果有mp3占用
        if(audio_device_multi_used) {
            sa_net_music_audio_play_pause(true);//mp3或者其他播放释放 notice@天飞
            app_sdk_audio_play_pause(false); //抢过来焦点
        }
       // mute_record(false);
    } else {
        //如果占用申请过来，停止播放就让出tts
        if(audio_device_multi_used) {
            app_sdk_audio_play_pause(true); //继续让出通道
            sa_net_music_audio_play_pause(false);//mp3或者其他播放获取 notice 给@天飞
        }
       // mute_record(true);
    }

}

// Callback implementations
void onErrorCallback(int errCode, const char* errMsg) {
    printf("Error occurred. Code: %d, Message: %s\n", errCode, errMsg);
}

void onCallStateChangeCallback(AGentCallState state) {

    printf("Call state changed: %d\n", state);
    if (state == AGENT_LOGIN_FAIL) {
        set_brtc_status(0);//服务器登录失败，请重新配置网络后点击登录
        printf("======================g_net_status_conneted_failed:===%s================================\r\n", AGENT_QUITE_NOTICE);
        play_mix_file(AGENT_QUITE_NOTICE);
    }
}

void onConnectionStateChangeCallback(AGentConnectState state) {
     //回调多次网络异常的情况
    printf("------------------------onConnectionStateChangeCallback--:%d--------------------------------------------------------------------------------", state);
    if (g_brtc_agent_abnormal_quit_first && (state == AGENT_CONNECTION_STATE_DISCONNECTED)){
            g_brtc_agent_abnormal_quit_first = false;
            if(!g_brtc_agent_normal_quit) {
                g_brtc_agent_abnormal_quit = 1;
            }
    }
    printf("Connection state changed: %d\n", state);
}

#define ASR_MAX_TEXT_LEN 256
static char g_asr_text_buffer[ASR_MAX_TEXT_LEN];
void onUserAsrSubtitleCallback(const char* text, size_t text_len, bool final, const ASRExtInfo* info) {
    time_last_asr = timer_get_ms();
    time_mute_play_mp3 = time_last_asr + 2000;
    if (audio_device_multi_used) {
        time_mute_play_mp3_valid = true;
        //-mp3_set_dec_volume_mute(4); //mp3静音操作
    }

   //final:true表示完整的一句话
    if (final) {
        if (text_len >= ASR_MAX_TEXT_LEN) { //text_len长度大于256时作了截断处理，客户不想截断的话，可以自己按需调整ASR_MAX_TEXT_LEN长度。
            text_len = ASR_MAX_TEXT_LEN - 1;
        }
        memcpy(g_asr_text_buffer, text, text_len);
        g_asr_text_buffer[text_len] = '\0';
        printf("User ASR subtitle: '%s', Name: %s, Emotion: %s, Score: %d, SessionId: %llu, (isFinal: %d)\n",
               g_asr_text_buffer,
               info->speakerName,
               info->emotion,
               info->similarity,
               info->sessionId,
               final);
    } else {
        printf("User ASR subtitle: '%s', Name: %s, Emotion: %s, Score: %d, SessionId: %llu, (isFinal: %d)\n",
           text,
           info->speakerName,
           info->emotion,
           info->similarity,
           info->sessionId,
           final);
    }
}

void onAIAgentSubtitleCallback(const char* text, int isFinal) {
    time_last_asr = timer_get_ms();
    printf("AIAgent ASR subtitle: %d %s (isFinal: %d)\n",timer_get_ms(), text, isFinal);
}

void onLicenseResult (bool result) {
    printf("onLicenseResult: %d\n", result);
    if (!result) {
        printf("onLicenseResult: failed\n");
        g_brtc_license_abnormal_exit = true;
        os_time_dly(10);
    }
}

void onAgentEventUpdated(const uint8_t* data, size_t len) {
    printf("onAgentEventUpdated: %s, len:%d\r\n", data, len);
    if (len == strlen(AGENT_EVENT_REMOTE_PLAYER_BEGIN) && strncmp(data, AGENT_EVENT_REMOTE_PLAYER_BEGIN, len) == 0){
         //g_remote_music_play = true;
        //setTTSMute(false);
    } else if (len == strlen(AGENT_EVENT_REMOTE_PLAYER_END) && strncmp(data, AGENT_EVENT_REMOTE_PLAYER_END, len) == 0) {
        //g_remote_music_play = false;
        //setTTSMute(true);
    }
}

extern int app_sdk_audio_play_volume(int level);
extern int app_sdk_audio_play_volume_step(int step);
extern int set_dec_volume(int step);
extern int set_dec_volume_step(int step);
extern void sa_audio_play(const char* url, bool type);

void onFunctionCall(const char* id, const char* params) {

    printf("onFunctionCall, id: %s, params: %s\n", id, params);
    json_object *obj = NULL;
    obj = json_tokener_parse(params);

    if (obj) {
        json_object* content  = json_object_object_get(obj, "content");
        if (content) {
            json_object* function_name  = json_object_object_get(content, "function_name");
            const char * function_name_str = json_object_get_string(function_name);

            if (!strcmp(function_name_str, "adjust_volume") || !strcmp(function_name_str, "play_control")) {
                json_object *parameter_list = json_object_object_get(content, "parameter_list");
                if (parameter_list) {
                    json_object *mode_obj = json_object_array_get_idx(parameter_list, 0);
                    json_object* mode  = json_object_object_get(mode_obj, "mode");
                    const char* mode_str = json_object_get_string(mode);

                    if (0 == strcmp(mode_str, "down")) {
                        set_dec_volume_step(-40);
                        app_sdk_audio_play_volume_step(-40);
                    }
                    else if (0 == strcmp(mode_str, "up")) {
                        set_dec_volume_step(40);
                        app_sdk_audio_play_volume_step(40);
                    }
                    else if (0 == strcmp(mode_str, "set")) {
                        json_object* mode_value = json_object_array_get_idx(parameter_list, 1);
                        json_object* value = json_object_object_get(mode_value, "value");
                        if (value != NULL) {
                            int volume = json_object_get_int(value);
                            //app_sdk_audio_play_pause(true);
                            app_sdk_audio_play_volume(volume);
                            set_dec_volume(volume);
                            //app_sdk_audio_play_pause(false);
                        }
                    }
                    else if (0 == strcmp(mode_str, "stop") ||　0 == strcmp(mode_str, "pause")) {
						app_sdk_audio_play_pause(false);
                        sa_audio_play("", 0);
                    }
                    if (!g_brtc_agent_normal_quit) {
                        baidu_chat_agent_engine_send_text_to_TTS(g_engine, "设置完成");
                    }
                }
            } else {
                printf("function_name:: %s",  function_name_str);
            }
        }
    }

    json_object_put(obj);
    if (!g_brtc_agent_normal_quit) {
        baidu_chat_agent_engine_send_functioncall_result(g_engine, id, "{\"result\":\"ok\"}");
    }

}

extern int app_sdk_audio_play_pause(bool);
extern void app_sdk_audio_play_stop();
extern int app_adk_play_pause();
void  onAudioPlayerOp(const char* path, bool start) {

    if (start) {
        //关闭本地播放
        //app_sdk_audio_play_stop();
        //app_sdk_audio_play_pause(true);
        // 开启音频播放

        if (g_brtc_speaking_tts) {
            //延迟播放音乐,
            g_brtc_delay_play_mp3 = true;
            strncpy(g_brtc_playurl, path, 1024);
            printf("[delay]  mp3_delay_url:%s\r\n", path);
        } else {
            app_sdk_audio_play_pause(true);
            sa_audio_play(path, start);
        }

    } else {
        app_adk_play_pause();
        app_sdk_audio_play_pause(false);
           // 网络音乐播放
        sa_audio_play(path, start);
    }

}


void onMediaSetup(void) {
    printf("Media setup completed.\n");
    baidu_chat_agent_engine_send_text_to_TTS(g_engine, "您好，我来了");
}

void onAudioData(const uint8_t* data, size_t len) {
    printf("Received audio data of length: %zu\n", len);
}

void onVideoData(const uint8_t* data, size_t len, int width, int height) {
    printf("Received video data of length: %zu, width: %d, height: %d\n", len, width, height);
}

void setUserParameters(AgentEngineParams *params) {
    snprintf(params->agent_platform_url, sizeof(params->agent_platform_url), "%s", SERVER_HOST_ONLINE);
    snprintf(params->appid, sizeof(params->appid), "%s", BDCloudDefaultRTCAppID);
    snprintf(params->userId, sizeof(params->userId), "%s", "12345678");
    snprintf(params->cer, sizeof(params->cer), "%s", "./a.cer");
    snprintf(params->workflow, sizeof(params->workflow), "%s", "VoiceChat");
    snprintf(params->license_key, sizeof(params->license_key), "%s", "a37483c9c21d44928b23a4fb03a8dcbd");

    params->instance_id = 10373;
    params->verbose = false;
    params->enable_internal_device =true;
    params->enable_local_agent =true;
    params->enable_voice_interrupt = true;
    params->level_voice_interrupt = 80;
    strncpy(params->llm, "LLMRacing", sizeof(params->llm) - 1);
    strncpy(params->lang, "zh", sizeof(params->lang) - 1);
    params->AudioInChannel = 1;
    params->AudioInFrequency = 16000;
    //params->enable_aec_inner = true;
    params->region = REGION_MAINLAND;  //默认是中国大陆
}

void baidu_chat_agent_demo_open(void* arg) {
    BaiduChatAgentEvent events = {
        .onError = onErrorCallback,
        .onCallStateChange = onCallStateChangeCallback,
        .onConnectionStateChange = onConnectionStateChangeCallback,
        .onUserAsrSubtitle = onUserAsrSubtitleCallback,
        .onAIAgentSubtitle = onAIAgentSubtitleCallback,
        .onAIAgentSpeaking = onAIAgentSpeaking,
        .onFunctionCall = onFunctionCall,
        .onAudioPlayerOp  = onAudioPlayerOp,
        .onMediaSetup = onMediaSetup,
        .onAudioData = onAudioData,
        .onVideoData = onVideoData,
        .onLicenseResult = onLicenseResult,
        .onAgentEventUpdated = onAgentEventUpdated,
    };

	struct AgentEngineParams* pAgentEngineParams = (struct AgentEngineParams*)arg;

    BaiduChatAgentEngine* engine = baidu_create_chat_agent_engine(&events);
    if (!engine) {
        printf("Engine initialization failed.\n");
        return;
    }
    g_engine = engine; // 保存全局变量供后续使用

    AgentEngineParams agentParams;
    memset(&agentParams, 0, sizeof(agentParams));
    setUserParameters(&agentParams);

    if (pAgentEngineParams) {
		agentParams.enable_local_agent = pAgentEngineParams->enable_local_agent;
		snprintf(agentParams.appid, sizeof(agentParams.appid), pAgentEngineParams->appid);
        snprintf(agentParams.remote_params, sizeof(agentParams.remote_params), pAgentEngineParams->remote_params);
        free(pAgentEngineParams);
    }

    printf("baidu_chat_agent_demo_open EEEEEEEEnd local:%d\n", agentParams.enable_local_agent);
    int result = baidu_chat_agent_engine_init(engine, &agentParams);
    if (result != 200) {
        printf("Failed to log in. Error code: %d\n", result);
        baidu_chat_agent_engine_destroy(engine);
        g_engine = NULL;
        return;
    }

    baidu_chat_agent_engine_call(engine);
}

void baidu_chat_agent_demo_close(void) {
    printf("baidu_chat_agent_demo_close__\n");
    if (g_engine) {
        printf("baidu_chat_agent_demo_close__2\n");
        baidu_chat_agent_engine_destroy(g_engine);
        g_engine = NULL;
        printf("baidu_chat_agent_demo_close__3\n");
    }
}
extern int sa_audio_is_net_music(void) ;
extern int play_mix_file(const char *path);
// 定时任务函数
static void timed_task(void *priv)
{
    g_brtc_agent_can_exit = true; //可以正常退出
    u32 cur_time = 0;
    while (1) {
        cur_time =  timer_get_ms();
        // 执行定时任务的工作
        //printf("ASR time_task: %d %d %d normal:%d, abnormal:%d,net_failed:%d, audio_device_multi_used:%d\n", \
        //    cur_time, time_last_asr, (cur_time - time_last_asr),g_brtc_agent_normal_quit,  g_brtc_agent_abnormal_quit,\
                g_net_status_conneted_failed, audio_device_multi_used);
        if (g_brtc_agent_abnormal_quit || g_net_status_conneted_failed || g_brtc_license_abnormal_exit
            || ((time_last_asr != 0) && (cur_time > time_last_asr + 300000) && (sa_audio_is_net_music() == 0)))
        {
            mute_record(false); //停止发送录音数据
            g_brtc_agent_normal_quit = true;
            set_brtc_status(0);
            if (g_brtc_license_abnormal_exit) {
                os_time_dly(400);
                printf("brtc license confirm failed ...\n");
            } else {
                printf("ASR no ai response over 5 min ...\n");
            }
            if (g_engine && !g_net_status_conneted_failed) {
                baidu_chat_agent_engine_send_text_to_TTS(g_engine, "我退下了");
                os_time_dly(1000);// 3秒 300个时钟 300*10
            } else {
                if (!g_brtc_agent_exit_quickly && g_net_status_conneted_failed) {
                    os_time_dly(300);// 3秒 300个时钟 300*10
                    play_mix_file(AGENT_QUITE_NOTICE);
                }\
                if (g_brtc_agent_abnormal_quit){
                    play_mix_file(AGENT_QUITE_NOTICE);
                }
            }
            time_last_asr = 0;
            printf("ASR baidu_chat_agent_engine_destroy ...\n");
            if (g_engine) {
                printf("baidu_chat_agent_engine_destroy__1\n");
                baidu_chat_agent_engine_destroy(g_engine);
                g_engine = NULL;
                printf("baidu_chat_agent_engine_destroy__2\n");
            }

            break;
        }
        if (kill_time_task_req) {
            if (g_engine) {
                printf("baidu_chat_agent_engine_destroy__3\n");
                baidu_chat_agent_engine_destroy(g_engine);
                g_engine = NULL;
                printf("baidu_chat_agent_engine_destroy__4\n");
            }
            os_time_dly(10);
            break;
        }

        //mute 音频mp3播放啦，停止mute
        /*if (g_net_status_conneted_failed || (time_mute_play_mp3_valid && cur_time > time_mute_play_mp3)){
            time_mute_play_mp3_valid = false;
            //play mp3 music if  necessary
            //onAIAgentSpeaking(false);
            mp3_set_dec_volume_reset();

        }*/

        //延迟播放，直到tts播放接受开始
        if (g_brtc_delay_play_mp3 && !g_brtc_speaking_tts) {

            app_sdk_audio_play_pause(true);

            g_brtc_delay_play_mp3 = false;
            // 网络音乐播放
            sa_audio_play(g_brtc_playurl, 1);
            printf("[mp3] real play");

        }

        // 延时一定时间（例如延时 1000 个 tick, 实际时间依赖于系统 tick 时钟配置）
        os_time_dly(50);
        //malloc_stats();
    }
    printf("%s\n", g_json_str);
    stopAIAgent(g_json_str);
    free(g_json_str);
    g_brtc_agent_can_exit = false;
}

void brtc_ai_agent_task_open(void* priv) {
    printf("brtc_ai_agent_task_open\n");

    struct AgentEngineParams* pAgentEngineParams = NULL;
    http_response_t* response = NULL;

    // 设置HTTP请求参数
    http_request_params_t request_params = {
        .url = GENERATE_AI_AGENT_CALL_URL,
        .method = HTTP_POST,
        .post_data = GENERATE_AI_AGENT_CALL_DATA,
        .content_type = "application/json",
        .timeout_ms = 5000,
        .custom_headers = NULL  // 如需要可以设置为 LOG_HTTP_HEAD_OPTION
    };

    // 发送HTTP请求
    response = send_http_request(&request_params);

    if (!response || !response->success) {
        printf("HTTP request failed\n");
        set_brtc_status(0);
        printf("=============11111====g_net_status_conneted_failed:===%s================================\r\n",
               AGENT_QUITE_NOTICE);
        play_mix_file(AGENT_QUITE_NOTICE);

        if (response) {
            free_http_response(response);
        }
        return;
    }

    // 请求成功，处理响应
    printf("\nReceive %d Bytes from (%s)\n", response->data_len, GENERATE_AI_AGENT_CALL_URL);
    printf("%s\n", response->data);

    g_json_str = malloc(response->data_len + 1);
    memcpy(g_json_str, response->data, response->data_len);
    g_json_str[response->data_len] = '\0';
    // 构造Agent引擎参数
    pAgentEngineParams = (struct AgentEngineParams*)zalloc(sizeof(struct AgentEngineParams));
    if (!pAgentEngineParams) {
        printf("Failed to allocate AgentEngineParams\n");
        free_http_response(response);
        set_brtc_status(0);
        return;
    }

    // 复制响应数据到参数结构体
    snprintf(pAgentEngineParams->remote_params,
             sizeof(pAgentEngineParams->remote_params),
             "%s", response->data);
    snprintf(pAgentEngineParams->appid,
             sizeof(pAgentEngineParams->appid),
             "%s", BRTC_APP_ID);

    // 释放HTTP响应
    free_http_response(response);

    // 设置Agent参数
    pAgentEngineParams->enable_local_agent = false;

        //init status
        time_last_asr = timer_get_ms();
        g_brtc_agent_normal_quit = false; //监控程序是否正常退出
        g_brtc_agent_abnormal_quit = false;
        g_brtc_agent_abnormal_quit_first = true;
        g_net_status_conneted_failed = false;
        g_brtc_agent_exit_quickly = false;

    // 创建任务
    int ret = thread_fork("baidu_chat_agent_demo_open", 21, 1024 * 96, 128,
                          &brtc_agent_task_pid,
                          (void*)baidu_chat_agent_demo_open,
                          pAgentEngineParams);
    printf("ret = %d\n", ret);

    // 创建定时任务
    thread_fork("timed_task", 10, 96 * 1024, 0,
                &time_task_pid, timed_task, NULL);
    printf("brtc_agent_task_pid:%d, time_task_pid:%d\n",
           brtc_agent_task_pid, time_task_pid);
}

void brtc_ai_agent_task_close(void* priv)
{
    printf("brtc_ai_agent_task_close brtc_agent_task_pid:%d, time_task_pid:%d\n", brtc_agent_task_pid, time_task_pid);
    if (brtc_agent_task_pid) {
        if (g_engine) {
            baidu_chat_agent_engine_destroy(g_engine);
            g_engine = NULL;
            set_brtc_status(0);
            printf("brtc_ai_agent_task_close destroy agent engine\n");
        }
        os_time_dly(20);
        thread_kill(&brtc_agent_task_pid, KILL_WAIT);
        brtc_agent_task_pid = 0;
    }

    if (time_task_pid) {
        kill_time_task_req = 1;
        os_time_dly(20);
        thread_kill(&time_task_pid, KILL_WAIT);
        time_task_pid = 0;
    }
}

void app_sdk_should_close(int quickly) {
    g_brtc_agent_exit_quickly = quickly;
    g_net_status_conneted_failed = true;
    //mp3播放 需要停止播放的。
    sa_audio_play("", 0);
}

bool app_brtc_agent_can_exit() {
    return g_brtc_agent_can_exit;
}

void app_brtc_agent_close_vad(bool start) {
    baidu_chat_agent_engine_send_event_to_agent(g_engine, ASR_EVENT_DISABLE_REALTIME);
    if (start) {
        os_time_dly(20);
        baidu_chat_agent_engine_send_event_to_agent(g_engine, ASR_EVENT_START_LONGTEXT_REC);
    } else {
        baidu_chat_agent_engine_send_event_to_agent(g_engine, ASR_EVENT_STOP_LONGTEXT_REC);
    }
}

void app_brtc_agent_asr_realtime(bool enable) {
    if (enable) {
        baidu_chat_agent_engine_send_event_to_agent(g_engine, ASR_EVENT_ENABLE_REALTIME);
    } else {
        baidu_chat_agent_engine_send_event_to_agent(g_engine, ASR_EVENT_DISABLE_REALTIME);
    }
}
