/**
 * @file scene_ai_study.c
 * @brief AI 拍学机场景实现
 */

#include "scene_ai_study.h"
#include "scene_ai_study_config.h"
#include "customer_tag.h"
#include "aiagent_engine.h"
#include "aiagent_credentials.h"
#include "hal_log.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define TAG "STUDY"

/* ========== 静态上下文 ========== */

static aiagent_engine_t s_engine = NULL;
static study_scene_type_t s_current_scene = STUDY_SCENE_VOICE_CHAT;
static void (*s_take_photo_cb)(void) = NULL;

/* ========== 配置 ========== */

static const aiagent_config_t s_study_config = {
    .ws_host = AIAGENT_WS_HOST,

    .appid          = AIAGENT_APPID,
    .license_key    = AIAGENT_LICENSE_KEY,
#if AIAGENT_CONN_MODE == AIAGENT_CONN_MODE_AKSK
    .access_key     = AIAGENT_ACCESS_KEY,
    .secret_key     = AIAGENT_SECRET_KEY,
#elif AIAGENT_CONN_MODE == AIAGENT_CONN_MODE_USERSERVER
    .userserver_url          = AIAGENT_USERSERVER_URL,
    .userserver_create_path  = AIAGENT_USERSERVER_CREATE,
    .userserver_destroy_path = AIAGENT_USERSERVER_DESTROY,
#endif

    .audio_codec = "g722",

    .cfg = {
        .lang          = "zh",
        .audiocodec    = "g722",
        .dfda          = true,
        .emotion_cfg   = "{\"enable\":true,\"injectToLLM\":true}",
        .voice_fp_url  = "{\"appId\":\"" AIAGENT_APPID "\",\"enable\":true,\"firstSentenceRegistration\":true,\"interruptMode\":0,\"enableClassifyOthers\":true,\"similarity\":[0.18,0.22,0.30,0.40]}",
        .enable_visual = true,
    },

    .audio_sample_rate      = AI_STUDY_SAMPLE_RATE,
    .audio_channels         = AI_STUDY_CHANNELS,
    .audio_frame_ms         = AI_STUDY_FRAME_MS,
    .default_mode           = AI_STUDY_DEFAULT_MODE,
    .aec_enable             = true,  /* 开启回声消除 */
};

static const aiagent_config_t *study_get_config(void)
{
    return &s_study_config;
}

/* ========== 子场景切换 ========== */

/* model_type: "2"=视觉 "3"=生图；prompt 为 NULL/空表示恢复默认 */
static void study_update_prompt(const char *model_type, const char *prompt)
{
    if (!s_engine) {
        return;
    }

    char json[4096];
    if (prompt && prompt[0]) {
        snprintf(json, sizeof(json),
                 "{\"model_type\":\"%s\",\"prompt\":\"%s\"}",
                 model_type, prompt);
    } else {
        snprintf(json, sizeof(json),
                 "{\"model_type\":\"%s\",\"prompt\":\"\"}",
                 model_type);
    }

    aiagent_engine_update_system_prompt(s_engine, json);
}

int study_scene_setup(study_scene_type_t scene_type)
{
    if (!s_engine || scene_type >= STUDY_SCENE_MAX) {
        return -1;
    }

    s_current_scene = scene_type;
    BD_LOGI(TAG, "切换子场景: %d", (int)scene_type);

    switch (scene_type) {
    case STUDY_SCENE_VOICE_CHAT:
        aiagent_engine_send_event(s_engine, STUDY_CMD_DISABLE_MEDIA_GEN);
        study_update_prompt(STUDY_MODEL_TYPE_VISION, NULL);
        study_update_prompt(STUDY_MODEL_TYPE_IMAGE_GEN, NULL);
        break;

    case STUDY_SCENE_IMAGE_UNDERSTANDING:
        /* 进入视觉理解模式 */
        aiagent_engine_send_event(s_engine, STUDY_CMD_DISABLE_MEDIA_GEN);
        aiagent_engine_update_visual_mode(s_engine, VISION_MODE_IMAGE, VISION_MODE_EXPIRE_SEC);
        study_update_prompt(STUDY_MODEL_TYPE_VISION, STUDY_VISION_PROMPT_IDENTIFY);
        break;

    case STUDY_SCENE_IMAGE_GENERATION:
        aiagent_engine_send_event(s_engine, STUDY_CMD_ENABLE_MEDIA_GEN);
        study_update_prompt(STUDY_MODEL_TYPE_IMAGE_GEN, NULL);
        break;

    case STUDY_SCENE_MULTI_MODAL:
        study_update_prompt(STUDY_MODEL_TYPE_VISION, STUDY_VISION_PROMPT_IDENTIFY);
        break;

    default:
        break;
    }

    return 0;
}

/**
 * @brief 切换视觉提示词
 * @param mode "identify"=拍万物, "shoot_chinese"=识中文, "shoot_english"=识英文
 */
int study_scene_set_vision_prompt(const char *mode)
{
    if (!s_engine || !mode) {
        return -1;
    }

    if (strcmp(mode, "identify") == 0) {
        study_update_prompt(STUDY_MODEL_TYPE_VISION, STUDY_VISION_PROMPT_IDENTIFY);
    } else if (strcmp(mode, "shoot_chinese") == 0) {
        study_update_prompt(STUDY_MODEL_TYPE_VISION, STUDY_VISION_PROMPT_CHINESE);
    } else if (strcmp(mode, "shoot_english") == 0) {
        study_update_prompt(STUDY_MODEL_TYPE_VISION, STUDY_VISION_PROMPT_ENGLISH);
    } else {
        BD_LOGW(TAG, "未知视觉模式: %s", mode);
        return -1;
    }

    BD_LOGI(TAG, "视觉提示词切换: %s", mode);
    return 0;
}

/**
 * @brief 设置文生图 Query 增强：用户语音被包装为 pre + speech + post
 * @param enhance_type 0=取消 1=前置 2=后置 3=前后
 */
int study_scene_set_enhance_query(int enhance_type, const char *pre_query, const char *post_query)
{
    if (!s_engine) {
        return -1;
    }

    const char *safe_pre  = pre_query  ? pre_query  : "";
    const char *safe_post = post_query ? post_query : "";

    char json[512];
    snprintf(json, sizeof(json),
             "{\"enhance_type\":\"%d\",\"pre_query\":\"%s\",\"post_query\":\"%s\"}",
             enhance_type, safe_pre, safe_post);

    BD_LOGI(TAG, "设置增强Query: type=%d, pre=%s, post=%s",
            enhance_type, safe_pre, safe_post);
    return aiagent_engine_set_enhance_query(s_engine, json);
}

int study_scene_send_image(const uint8_t *jpeg_data, size_t jpeg_len)
{
    if (!s_engine || !jpeg_data || jpeg_len == 0) {
        return -1;
    }

    BD_LOGI(TAG, "发送图片: %d bytes", (int)jpeg_len);
    return aiagent_engine_send_video(s_engine, jpeg_data, jpeg_len);
}

void study_scene_register_photo_callback(void (*cb)(void))
{
    s_take_photo_cb = cb;
}

/* ========== 场景生命周期 ========== */

static int study_on_init(aiagent_engine_t engine)
{
    s_engine = engine;
    s_current_scene = STUDY_SCENE_VOICE_CHAT;
    BD_LOGI(TAG, "AI拍学机场景初始化");
    return 0;
}

static void study_on_start(aiagent_engine_t engine)
{
    BD_LOGI(TAG, "AI拍学机场景启动");
}

static void study_on_stop(aiagent_engine_t engine)
{
    BD_LOGI(TAG, "AI拍学机场景停止");
    s_engine = NULL;
    s_current_scene = STUDY_SCENE_VOICE_CHAT;
}

static void study_on_destroy(void)
{
    BD_LOGI(TAG, "AI拍学机场景销毁");
    s_take_photo_cb = NULL;
}

/* ========== 事件回调 ========== */

static void study_on_state_change(aiagent_state_t old_st, aiagent_state_t new_st)
{
    BD_LOGD(TAG, "状态变化: %d -> %d", old_st, new_st);

    /* license PASS 后首次进入 READY 时下发子场景配置 */
    if (old_st == AIAGENT_STATE_CONNECTING && new_st == AIAGENT_STATE_READY) {
        study_scene_setup(STUDY_SCENE_IMAGE_UNDERSTANDING);
    }
}

static void study_on_asr_result(const char *text, bool is_final, const aiagent_asr_ext_t *ext)
{
    if (!is_final) {
        return;
    }
    if (ext && ext->emotion) {
        BD_LOGI(TAG, "ASR final: \"%s\"  emotion=[%s] name=[%s]",
                text ? text : "",
                ext->emotion,
                ext->name ? ext->name : "-");
    } else {
        BD_LOGI(TAG, "ASR final: \"%s\"", text ? text : "");
    }
}

/* 支持 take_photo */
static int study_on_function_call(const char *session_id, const char *name,
                                    const char *params)
{
    BD_LOGI(TAG, "FC: name=%s", name ? name : "null");

    if (name && strcmp(name, "take_photo") == 0) {
        if (s_take_photo_cb) {
            s_take_photo_cb();
        }
        if (s_engine && session_id) {
            aiagent_engine_send_fc_result(s_engine, session_id, "ok", "photo_taken");
        }
        return 1;
    }

    return 0;
}

static void study_on_event(aiagent_event_type_t event, const char *data,
                            size_t data_len)
{
    switch (event) {
    case AIAGENT_EVT_UPLOAD_IMAGE:
        BD_LOGI(TAG, "收到图片上传请求");
        if (s_take_photo_cb) {
            s_take_photo_cb();
        }
        break;

    case AIAGENT_EVT_TAG_MSG: {
        BD_LOGI(TAG, "收到TAG消息: len=%d", (int)data_len);
        /* 堆上分配解析结果 */
        tag_msg_info_t *tag_info = (tag_msg_info_t *)malloc(sizeof(*tag_info));
        if (!tag_info) {
            BD_LOGW(TAG, "TAG解析: 内存不足");
            break;
        }
        if (tag_msg_parse(data, data_len, tag_info)) {
            BD_LOGI(TAG, "TAG解析成功: type=%s", tag_msg_type_name(tag_info->type));
            /* TAG 结果已解析，可在此对接业务界面 */
        } else {
            BD_LOGW(TAG, "TAG解析失败");
        }
        free(tag_info);
        break;
    }

    case AIAGENT_EVT_MEDIA_GEN_RESULT:
        BD_LOGI(TAG, "收到图片生成结果: len=%d data=%.*s",
                (int)data_len, (int)data_len, data ? data : "");
        /* 图片生成结果已返回，可在此对接展示或下载流程 */
        break;

    default:
        break;
    }
}

static void study_on_key_event(int action, int key_value)
{
    BD_LOGD(TAG, "按键事件: action=%d, key=%d", action, key_value);
}

static void study_on_network_event(int event)
{
    BD_LOGI(TAG, "网络事件: %d", event);
}

/* ========== 场景注册 ========== */

static const aiagent_scene_ops_t s_study_ops = {
    .name             = "ai_study",
    .get_config       = study_get_config,
    .on_init          = study_on_init,
    .on_start         = study_on_start,
    .on_stop          = study_on_stop,
    .on_destroy       = study_on_destroy,
    .on_state_change  = study_on_state_change,
    .on_asr_result    = study_on_asr_result,
    .on_function_call = study_on_function_call,
    .on_event         = study_on_event,
    .on_key_event     = study_on_key_event,
    .on_network_event = study_on_network_event,
};

const aiagent_scene_ops_t *scene_ai_study_get_ops(void)
{
    return &s_study_ops;
}
