    #include <jni.h>
#include <string>
#include <android/log.h>
#include <memory>
#include <vector>
#include <map>
#include <cstring>
#include "../include/cpp/add.h"
#include "../include/cpp/data_praser.h"
#include "../include/cpp/signal_processor.h"
#include "../include/cpp/data_mapper.h"
#include "../include/cpp/indicator_cal.h"

using core::math::add;

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_cmake_1project_1test_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++ (multi-file)";
    return env->NewStringUTF(hello.c_str());
}

extern "C" JNIEXPORT jint JNICALL
Java_com_example_cmake_1project_1test_MainActivity_addFromJNI(
        JNIEnv* env,
        jobject /* this */,
        jint a,
        jint b) {
    (void)env;
    return static_cast<jint>(add(static_cast<int>(a), static_cast<int>(b)));
}

extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_MainActivity_parseDeviceDataFromJNI(
        JNIEnv* env,
        jobject /* this */,
        jbyteArray fileData) {
    
    try {
        // 将Java的byte数组转换为C++的vector
        std::vector<uint8_t> cppFileData = convertJavaByteArrayToVector(env, fileData);
        
        if (cppFileData.empty()) {
            __android_log_print(ANDROID_LOG_WARN, "DataParser", "Empty file data received");
            return nullptr;
        }
        
        // 调用C++的解析函数
        std::vector<SensorData> result = parse_device_data(cppFileData);
        
        // 将结果转换为Java对象
        jobject javaResult = convertSensorDataVectorToJavaList(env, result);
        
        if (javaResult == nullptr) {
            __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Failed to convert result to Java object");
        } else {
            __android_log_print(ANDROID_LOG_INFO, "DataParser", "Successfully parsed %zu data packets", result.size());
        }
        
        return javaResult;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Exception during parsing: %s", e.what());
        return nullptr;
    } catch (...) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Unknown exception during parsing");
        return nullptr;
    }
}


// ================= 流式解析 JNI 接口 =================

// 创建解析器实例，返回 native 句柄
extern "C" JNIEXPORT jlong JNICALL
Java_com_example_cmake_1project_1test_MainActivity_createStreamParser(
        JNIEnv* env,
        jobject /* this */) {
    (void)env;
    try {
        auto* parser = new StreamParser();
        return reinterpret_cast<jlong>(parser);
    } catch (...) {
        return 0;
    }
}

// 释放解析器实例
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_MainActivity_destroyStreamParser(
        JNIEnv* env,
        jobject /* this */,
        jlong handle) {
    (void)env;
    if (handle == 0) return; // 避免删除空指针
    
    auto* parser = reinterpret_cast<StreamParser*>(handle);
    if (parser) {
        delete parser;
    }
}

// 追加一段字节流数据
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_MainActivity_streamParserAppend(
        JNIEnv* env,
        jobject /* this */,
        jlong handle,
        jbyteArray chunk) {
    if (handle == 0 || !chunk) return; // 检查句柄和输入
    
    auto* parser = reinterpret_cast<StreamParser*>(handle);
    if (!parser) return;

    jsize len = env->GetArrayLength(chunk);
    if (len <= 0) return;
    std::vector<uint8_t> buf(static_cast<size_t>(len));
    env->GetByteArrayRegion(chunk, 0, len, reinterpret_cast<jbyte*>(buf.data()));
    parser->appendData(buf.data(), buf.size());
}

// 拉取已完成的所有数据包，转换为 Java List<SensorData>
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_MainActivity_streamParserDrainPackets(
        JNIEnv* env,
        jobject /* this */,
        jlong handle) {
    if (handle == 0) return nullptr; // 检查句柄
    
    auto* parser = reinterpret_cast<StreamParser*>(handle);
    if (!parser) return nullptr;
    
    try {
        std::vector<SensorData> packets = parser->getAllPackets();
        return convertSensorDataVectorToJavaList(env, packets);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "StreamParser", "Exception in drainPackets: %s", e.what());
        return nullptr;
    } catch (...) {
        __android_log_print(ANDROID_LOG_ERROR, "StreamParser", "Unknown exception in drainPackets");
        return nullptr;
    }
}


// ================= 信号处理 JNI 接口 =================

// 全局变量存储SignalProcessor实例
static std::map<jlong, std::unique_ptr<SignalProcessor>> processor_instances;
static jlong next_processor_id = 1;

// 辅助函数：将Java字节数组转换为C++向量
std::vector<float> java_byte_array_to_vector(JNIEnv* env, jbyteArray java_array) {
    if (java_array == nullptr) return {};
    
    jsize length = env->GetArrayLength(java_array);
    jbyte* bytes = env->GetByteArrayElements(java_array, nullptr);
    
    std::vector<float> result;
    result.reserve(length / sizeof(float));
    
    for (int i = 0; i < length; i += sizeof(float)) {
        float value;
        memcpy(&value, &bytes[i], sizeof(float));
        result.push_back(value);
    }
    
    env->ReleaseByteArrayElements(java_array, bytes, JNI_ABORT);
    return result;
}

// 辅助函数：将C++向量转换为Java字节数组
jbyteArray vector_to_java_byte_array(JNIEnv* env, const std::vector<float>& vec) {
    jsize length = vec.size() * sizeof(float);
    jbyteArray result = env->NewByteArray(length);
    
    if (result != nullptr) {
        jbyte* bytes = env->GetByteArrayElements(result, nullptr);
        for (size_t i = 0; i < vec.size(); ++i) {
            memcpy(&bytes[i * sizeof(float)], &vec[i], sizeof(float));
        }
        env->ReleaseByteArrayElements(result, bytes, 0);
    }
    
    return result;
}

// JNI函数：创建SignalProcessor实例
extern "C" JNIEXPORT jlong JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_createSignalProcessor(JNIEnv* env, jobject thiz) {
    try {
        auto processor = std::make_unique<SignalProcessor>();
        jlong id = next_processor_id++;
        processor_instances[id] = std::move(processor);
        return id;
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Failed to create processor: %s", e.what());
        return -1;
    }
}

// JNI函数：销毁SignalProcessor实例
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_destroySignalProcessor(JNIEnv* env, jobject thiz, jlong processor_id) {
    auto it = processor_instances.find(processor_id);
    if (it != processor_instances.end()) {
        processor_instances.erase(it);
    }
}

// JNI函数：带通滤波
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_bandpassFilter(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate, jdouble low_freq, jdouble high_freq) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        std::vector<float> result = it->second->bandpass_filter(signal_vec, sample_rate, low_freq, high_freq);
        return vector_to_java_byte_array(env, result);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Bandpass filter error: %s", e.what());
        return nullptr;
    }
}

// JNI函数：低通滤波
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_lowpassFilter(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate, jdouble cutoff_freq) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        std::vector<float> result = it->second->Lowpass_filter(signal_vec, sample_rate, cutoff_freq);
        return vector_to_java_byte_array(env, result);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Lowpass filter error: %s", e.what());
        return nullptr;
    }
}

// JNI函数：高通滤波
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_highpassFilter(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate, jdouble cutoff_freq) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        std::vector<float> result = it->second->Highpass_filter(signal_vec, sample_rate, cutoff_freq);
        return vector_to_java_byte_array(env, result);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Highpass filter error: %s", e.what());
        return nullptr;
    }
}

// JNI函数：陷波滤波
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_notchFilter(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate, jdouble notch_freq, jdouble q_factor) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        // 使用自适应陷波滤波器
        std::vector<float> result = it->second->adaptive_notch_filter(signal_vec, sample_rate, notch_freq, q_factor);
        return vector_to_java_byte_array(env, result);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Notch filter error: %s", e.what());
        return nullptr;
    }
}

// JNI函数：计算信号质量
extern "C" JNIEXPORT jfloat JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_calculateSignalQuality(
    JNIEnv* env, jobject thiz, jlong processor_id, jbyteArray signal) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return 0.0f;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        // 使用SNR作为信号质量指标
        return it->second->calculate_snr(signal_vec);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Signal quality calculation error: %s", e.what());
        return 0.0f;
    }
}

// JNI函数：计算ECG信号质量指数
extern "C" JNIEXPORT jfloat JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_calculateECGSQI(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return 0.0f;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        return it->second->calculate_ecg_sqi(signal_vec, sample_rate);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "ECG SQI calculation error: %s", e.what());
        return 0.0f;
    }
}

// JNI函数：计算相关性
extern "C" JNIEXPORT jfloat JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_calculateCorrelation(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray x, jbyteArray y) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return 0.0f;
    
    try {
        std::vector<float> x_vec = java_byte_array_to_vector(env, x);
        std::vector<float> y_vec = java_byte_array_to_vector(env, y);
        return it->second->calculate_correlation(x_vec, y_vec);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Correlation calculation error: %s", e.what());
        return 0.0f;
    }
}

// JNI函数：归一化幅度
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_normalizeAmplitude(
    JNIEnv* env, jobject thiz, jlong processor_id, jbyteArray signal) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        it->second->normalize_amplitude(signal_vec);
        
        // 将处理后的数据写回Java数组
        jsize length = env->GetArrayLength(signal);
        jbyte* bytes = env->GetByteArrayElements(signal, nullptr);
        for (size_t i = 0; i < signal_vec.size(); ++i) {
            memcpy(&bytes[i * sizeof(float)], &signal_vec[i], sizeof(float));
        }
        env->ReleaseByteArrayElements(signal, bytes, 0);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Normalize amplitude error: %s", e.what());
    }
}

// JNI函数：提取特征
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_extractFeatures(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray signal, jdouble sample_rate) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> signal_vec = java_byte_array_to_vector(env, signal);
        // 创建临时的SensorData对象来调用特征提取
        SensorData temp_data;
        temp_data.data_type = DataType::EEG; // 默认类型
        temp_data.channel_data = std::vector<std::vector<float>>{signal_vec};
        
        FeatureSet features = it->second->extract_signal_features(temp_data);
        
        // 将特征转换为float数组（简化处理）
        std::vector<float> feature_vector;
        // 这里可以根据实际需要提取具体的特征值
        // 暂时返回原始信号作为特征
        feature_vector = signal_vec;
        
        return vector_to_java_byte_array(env, feature_vector);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Feature extraction error: %s", e.what());
        return nullptr;
    }
}

// JNI函数：重置滤波器
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_resetFilters(
    JNIEnv* env, jobject thiz, jlong processor_id) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return;
    
    try {
        // 清除滤波器状态
        it->second->filter_states_.clear();
        __android_log_print(ANDROID_LOG_INFO, "SignalProcessor", "Filters reset successfully");
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Reset filters error: %s", e.what());
    }
}

// JNI函数：实时处理数据块
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_example_cmake_1project_1test_SignalProcessorJNI_processRealtimeChunk(
    JNIEnv* env, jobject thiz, jlong processor_id, 
    jbyteArray chunk, jdouble sample_rate) {
    
    auto it = processor_instances.find(processor_id);
    if (it == processor_instances.end()) return nullptr;
    
    try {
        std::vector<float> chunk_vec = java_byte_array_to_vector(env, chunk);
        
        // 应用基本的预处理
        std::vector<float> processed = it->second->remove_dc_offset(chunk_vec);
        processed = it->second->remove_motion_artifacts(processed, sample_rate);
        
                return vector_to_java_byte_array(env, processed);
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "SignalProcessor", "Real-time processing error: %s", e.what());
        return nullptr;
    }
}

// 便捷方法：从整块数据按固定块大小模拟流式解析，返回解析到的所有包
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_MainActivity_parseStreamFromBytes(
    JNIEnv* env,
    jobject /* this */,
    jbyteArray data,
    jint chunkSize) {
    if (data == nullptr || chunkSize <= 0) return nullptr;

    std::vector<uint8_t> src = convertJavaByteArrayToVector(env, data);
    auto* parser = new StreamParser();
    size_t offset = 0;
    while (offset < src.size()) {
        size_t n = std::min(static_cast<size_t>(chunkSize), src.size() - offset);
        parser->appendData(src.data() + offset, n);
        offset += n;
    }
    std::vector<SensorData> packets = parser->getAllPackets();
    delete parser;
    return convertSensorDataVectorToJavaList(env, packets);
}

// ============================================================================
// DataMapper JNI函数实现
// ============================================================================

// 创建数据映射器实例
extern "C" JNIEXPORT jlong JNICALL
Java_com_example_cmake_1project_1test_DataMapper_createDataMapper(
    JNIEnv* env, jobject thiz) {
    try {
        Mapper* mapper = new Mapper();
        jlong mapperId = reinterpret_cast<jlong>(mapper);
        
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Created DataMapper instance with ID: %lld", mapperId);
        return mapperId;
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Failed to create DataMapper: %s", e.what());
        return 0;
    }
}

// 销毁数据映射器实例
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_DataMapper_destroyDataMapper(
    JNIEnv* env, jobject thiz, jlong mapperHandle) {
    try {
        if (mapperHandle != 0) {
            Mapper* mapper = reinterpret_cast<Mapper*>(mapperHandle);
            delete mapper;
            __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Destroyed DataMapper instance with ID: %lld", mapperHandle);
        } else {
            __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Attempted to destroy null DataMapper handle");
        }
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Failed to destroy DataMapper: %s", e.what());
    }
}

// 映射单个数据包
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_DataMapper_mapSensorData(
    JNIEnv* env, jobject thiz, jlong mapperHandle, jobject sensorData) {
    try {
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== JNI mapSensorData被调用 ===");
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "mapperHandle: %ld", mapperHandle);
        
        if (mapperHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Invalid mapper handle: 0");
            return nullptr;
        }
        
        Mapper* mapper = reinterpret_cast<Mapper*>(mapperHandle);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Mapper指针获取成功");
        
        // 将Java的SensorData转换为C++的SensorData
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "开始转换Java SensorData到C++");
        SensorData cppSensorData = convertJavaSensorDataToCpp(env, sensorData);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Java到C++转换完成");
        
        // 执行映射
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "开始调用C++ DataMapper函数");
        SensorData mappedData = mapper->DataMapper(cppSensorData);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "C++ DataMapper函数调用完成");
        
        // 将C++的SensorData转换回Java对象
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "开始转换C++ SensorData到Java");
        jobject result = convertSensorDataToJava(env, mappedData);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "C++到Java转换完成");
        
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Successfully mapped sensor data");
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Failed to map sensor data: %s", e.what());
        return nullptr;
    }
}

// 批量映射数据包
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_DataMapper_mapSensorDataList(
    JNIEnv* env, jobject thiz, jlong mapperHandle, jobject sensorDataList) {
    try {
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== JNI mapSensorDataList被调用 ===");
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "mapperHandle: %lld", mapperHandle);
        
        if (mapperHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Invalid mapper handle: 0");
            return nullptr;
        }
        
        Mapper* mapper = reinterpret_cast<Mapper*>(mapperHandle);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Mapper指针获取成功");
        
        // 将Java的List<SensorData>转换为C++的vector<SensorData>
        std::vector<SensorData> cppSensorDataList = convertJavaSensorDataListToVector(env, sensorDataList);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "转换后的数据包数量: %zu", cppSensorDataList.size());
        
        // 批量映射
        std::vector<SensorData> mappedDataList;
        mappedDataList.reserve(cppSensorDataList.size());
        
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "开始批量映射，数据包数量: %zu", cppSensorDataList.size());
        
        for (size_t i = 0; i < cppSensorDataList.size(); ++i) {
            try {
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "处理第 %zu 个数据包", i + 1);
                SensorData mappedData = mapper->DataMapper(cppSensorDataList[i]);
                mappedDataList.push_back(mappedData);
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "第 %zu 个数据包映射完成", i + 1);
            } catch (const std::exception& e) {
                __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Failed to map individual sensor data: %s", e.what());
                // 如果单个数据包映射失败，保留原始数据
                mappedDataList.push_back(cppSensorDataList[i]);
            }
        }
        
        // 将C++的vector<SensorData>转换回Java的List
        jobject result = convertSensorDataVectorToJavaList(env, mappedDataList);
        
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "Successfully mapped %zu sensor data packets", mappedDataList.size());
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Failed to map sensor data list: %s", e.what());
        return nullptr;
    }
}

// ============================================================================
// 辅助函数实现
// ============================================================================

// 将Java的SensorData转换为C++的SensorData
SensorData convertJavaSensorDataToCpp(JNIEnv* env, jobject javaSensorData) {
    SensorData cppSensorData;
    
    // 获取Java类的引用
    jclass sensorDataClass = env->GetObjectClass(javaSensorData);
    
    // 获取字段ID
    jfieldID dataTypeField = env->GetFieldID(sensorDataClass, "dataType", "Ltype/SensorData$DataType;");
    jfieldID packetSnField = env->GetFieldID(sensorDataClass, "packetSn", "I");
    jfieldID leadStatusField = env->GetFieldID(sensorDataClass, "leadStatus", "[B");
    jfieldID timestampField = env->GetFieldID(sensorDataClass, "timestamp", "J");
    jfieldID channelDataField = env->GetFieldID(sensorDataClass, "channelData", "Ljava/util/List;");
    jfieldID additionalDataField = env->GetFieldID(sensorDataClass, "additionalData", "Ltype/SensorData$AdditionalData;");
    jfieldID rawDataField = env->GetFieldID(sensorDataClass, "rawData", "[B");
    
    // 读取基本字段
    cppSensorData.packet_sn = env->GetIntField(javaSensorData, packetSnField);
    cppSensorData.timestamp = env->GetLongField(javaSensorData, timestampField);
    
    // 读取数据类型
    jobject dataTypeObj = env->GetObjectField(javaSensorData, dataTypeField);
    if (dataTypeObj != nullptr) {
        jclass dataTypeClass = env->GetObjectClass(dataTypeObj);
        jmethodID nameMethod = env->GetMethodID(dataTypeClass, "name", "()Ljava/lang/String;");
        jstring nameStr = (jstring)env->CallObjectMethod(dataTypeObj, nameMethod);
        const char* name = env->GetStringUTFChars(nameStr, nullptr);
        
        if (strcmp(name, "EEG") == 0) cppSensorData.data_type = DataType::EEG;
        else if (strcmp(name, "ECG_2LEAD") == 0) cppSensorData.data_type = DataType::ECG_2LEAD;
        else if (strcmp(name, "ECG_12LEAD") == 0) cppSensorData.data_type = DataType::ECG_12LEAD;
        else if (strcmp(name, "PPG") == 0) cppSensorData.data_type = DataType::PPG;
        else if (strcmp(name, "RESPIRATION") == 0) cppSensorData.data_type = DataType::RESPIRATION;
        else if (strcmp(name, "SNORE") == 0) cppSensorData.data_type = DataType::SNORE;
        else if (strcmp(name, "STETHOSCOPE") == 0) cppSensorData.data_type = DataType::STETHOSCOPE;
        else cppSensorData.data_type = DataType::EEG; // 默认值
        
        env->ReleaseStringUTFChars(nameStr, name);
    }
    
    // 读取导联状态
    jbyteArray leadStatusArray = (jbyteArray)env->GetObjectField(javaSensorData, leadStatusField);
    if (leadStatusArray != nullptr) {
        jbyte* elements = env->GetByteArrayElements(leadStatusArray, nullptr);
        std::memcpy(cppSensorData.lead_status.status, elements, 2);
        env->ReleaseByteArrayElements(leadStatusArray, elements, JNI_ABORT);
    }
    
    // 读取通道数据
    jobject channelDataList = env->GetObjectField(javaSensorData, channelDataField);
    if (channelDataList != nullptr) {
        jclass listClass = env->GetObjectClass(channelDataList);
        jmethodID sizeMethod = env->GetMethodID(listClass, "size", "()I");
        jmethodID getMethod = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;");
        
        jint listSize = env->CallIntMethod(channelDataList, sizeMethod);
        
        if (listSize > 0) {
            try {
                // 检查第一个元素是List还是Float
                jobject firstElement = env->CallObjectMethod(channelDataList, getMethod, 0);
                if (firstElement != nullptr) {
                    jclass elementClass = env->GetObjectClass(firstElement);
                    jclass listClassRef = env->FindClass("java/util/List");
                    
                    if (listClassRef != nullptr && env->IsInstanceOf(firstElement, listClassRef)) {
                        // 多通道数据 (List<List<Float>>)
                        std::vector<std::vector<float>> channels;
                        channels.reserve(listSize);
                        
                        for (int i = 0; i < listSize; i++) {
                            jobject channelList = env->CallObjectMethod(channelDataList, getMethod, i);
                            if (channelList != nullptr) {
                                std::vector<float> channel = convertJavaFloatListToVector(env, channelList);
                                channels.push_back(channel);
                            }
                        }
                        
                        cppSensorData.channel_data = channels;
                    } else {
                        // 单通道数据 (List<Float>)
                        std::vector<float> channel = convertJavaFloatListToVector(env, channelDataList);
                        cppSensorData.channel_data = channel;
                    }
                } else {
                    // 第一个元素为空，假设是单通道数据
                    std::vector<float> channel = convertJavaFloatListToVector(env, channelDataList);
                    cppSensorData.channel_data = channel;
                }
            } catch (...) {
                // 如果转换失败，创建一个空的通道数据
                std::vector<float> emptyChannel;
                cppSensorData.channel_data = emptyChannel;
            }
        } else {
            // 空列表，创建空的通道数据
            std::vector<float> emptyChannel;
            cppSensorData.channel_data = emptyChannel;
        }
    } else {
        // 通道数据为空，创建空的通道数据
        std::vector<float> emptyChannel;
        cppSensorData.channel_data = emptyChannel;
    }
    
    // 读取原始数据
    jbyteArray rawDataArray = (jbyteArray)env->GetObjectField(javaSensorData, rawDataField);
    if (rawDataArray != nullptr) {
        jsize length = env->GetArrayLength(rawDataArray);
        jbyte* elements = env->GetByteArrayElements(rawDataArray, nullptr);
        cppSensorData.raw_data.assign(elements, elements + length);
        env->ReleaseByteArrayElements(rawDataArray, elements, JNI_ABORT);
    }
    
    return cppSensorData;
}

// 将Java的Float List转换为C++的vector<float>
std::vector<float> convertJavaFloatListToVector(JNIEnv* env, jobject floatList) {
    std::vector<float> result;
    
    try {
        jclass listClass = env->GetObjectClass(floatList);
        jmethodID sizeMethod = env->GetMethodID(listClass, "size", "()I");
        jmethodID getMethod = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;");
        
        jint listSize = env->CallIntMethod(floatList, sizeMethod);
        result.reserve(listSize);
        
        for (int i = 0; i < listSize; i++) {
            jobject floatObj = env->CallObjectMethod(floatList, getMethod, i);
            if (floatObj != nullptr) {
                // 尝试使用Float.floatValue()方法
                jclass floatClass = env->GetObjectClass(floatObj);
                jmethodID floatValueMethod = env->GetMethodID(floatClass, "floatValue", "()F");
                if (floatValueMethod != nullptr) {
                    float value = env->CallFloatMethod(floatObj, floatValueMethod);
                    result.push_back(value);
                } else {
                    // 如果floatValue方法不存在，尝试直接访问value字段
                    jfieldID valueField = env->GetFieldID(floatClass, "value", "F");
                    if (valueField != nullptr) {
                        float value = env->GetFloatField(floatObj, valueField);
                        result.push_back(value);
                    } else {
                        // 如果都失败了，使用默认值
                        result.push_back(0.0f);
                    }
                }
            } else {
                // 如果对象为null，使用默认值
                result.push_back(0.0f);
            }
        }
    } catch (...) {
        // 如果转换失败，返回空向量
        result.clear();
    }
    
    return result;
}

// 将Java的List<SensorData>转换为C++的vector<SensorData>
std::vector<SensorData> convertJavaSensorDataListToVector(JNIEnv* env, jobject sensorDataList) {
    std::vector<SensorData> result;
    
    jclass listClass = env->GetObjectClass(sensorDataList);
    jmethodID sizeMethod = env->GetMethodID(listClass, "size", "()I");
    jmethodID getMethod = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;");
    
    jint listSize = env->CallIntMethod(sensorDataList, sizeMethod);
    result.reserve(listSize);
    
    for (int i = 0; i < listSize; i++) {
        jobject sensorDataObj = env->CallObjectMethod(sensorDataList, getMethod, i);
        SensorData cppSensorData = convertJavaSensorDataToCpp(env, sensorDataObj);
        result.push_back(cppSensorData);
    }
    
    return result;
}

// ============================================================================
// IndicatorCalculator JNI函数实现
// ============================================================================

// 创建指标计算器实例
extern "C" JNIEXPORT jlong JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_createIndicatorCalculator(
    JNIEnv* env, jobject thiz) {
    try {
        MetricsCalculator* calculator = new MetricsCalculator();
        jlong calculatorId = reinterpret_cast<jlong>(calculator);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Created IndicatorCalculator instance with ID: %lld", calculatorId);
        return calculatorId;
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to create IndicatorCalculator: %s", e.what());
        return 0;
    }
}

// 销毁指标计算器实例
extern "C" JNIEXPORT void JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_destroyIndicatorCalculator(
    JNIEnv* env, jobject thiz, jlong calculatorHandle) {
    try {
        if (calculatorHandle != 0) {
            MetricsCalculator* calculator = reinterpret_cast<MetricsCalculator*>(calculatorHandle);
            delete calculator;
            __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Destroyed IndicatorCalculator instance with ID: %lld", calculatorHandle);
        } else {
            __android_log_print(ANDROID_LOG_WARN, "IndicatorCalculator", "Attempted to destroy null IndicatorCalculator handle");
        }
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to destroy IndicatorCalculator: %s", e.what());
    }
}

// 完整数据处理流程
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_processCompletePipeline(
    JNIEnv* env, jobject thiz, jlong calculatorHandle, jobject sensorData, jfloat sampleRate) {
    try {
        if (calculatorHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Invalid calculator handle: 0");
            return nullptr;
        }
        
        MetricsCalculator* calculator = reinterpret_cast<MetricsCalculator*>(calculatorHandle);
        
        // 将Java的SensorData转换为C++的SensorData
        SensorData cppSensorData = convertJavaSensorDataToCpp(env, sensorData);
        
        // 执行完整的数据处理流程
        std::map<std::string, float> metrics = calculator->process_complete_pipeline(cppSensorData, sampleRate);
        
        // 将C++的map转换为Java的Map
        jobject result = convertMetricsMapToJava(env, metrics);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Successfully processed complete pipeline, calculated %zu metrics", metrics.size());
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to process complete pipeline: %s", e.what());
        return nullptr;
    }
}

// 计算ECG指标
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_calculateECGMetrics(
    JNIEnv* env, jobject thiz, jlong calculatorHandle, jobject sensorData, jfloat sampleRate) {
    try {
        if (calculatorHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Invalid calculator handle: 0");
            return nullptr;
        }
        
        MetricsCalculator* calculator = reinterpret_cast<MetricsCalculator*>(calculatorHandle);
        
        // 将Java的SensorData转换为C++的SensorData
        SensorData cppSensorData = convertJavaSensorDataToCpp(env, sensorData);
        
        // 计算ECG指标
        std::map<std::string, float> metrics = calculator->calculate_all_ecg_metrics(cppSensorData, sampleRate);
        
        // 将C++的map转换为Java的Map
        jobject result = convertMetricsMapToJava(env, metrics);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Successfully calculated ECG metrics, %zu metrics", metrics.size());
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to calculate ECG metrics: %s", e.what());
        return nullptr;
    }
}

// 计算PPG指标
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_calculatePPGMetrics(
    JNIEnv* env, jobject thiz, jlong calculatorHandle, jobject sensorData, jfloat sampleRate) {
    try {
        if (calculatorHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Invalid calculator handle: 0");
            return nullptr;
        }
        
        MetricsCalculator* calculator = reinterpret_cast<MetricsCalculator*>(calculatorHandle);
        
        // 将Java的SensorData转换为C++的SensorData
        SensorData cppSensorData = convertJavaSensorDataToCpp(env, sensorData);
        
        // 计算PPG指标
        std::map<std::string, float> metrics = calculator->calculate_all_ppg_metrics(cppSensorData, sampleRate);
        
        // 将C++的map转换为Java的Map
        jobject result = convertMetricsMapToJava(env, metrics);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Successfully calculated PPG metrics, %zu metrics", metrics.size());
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to calculate PPG metrics: %s", e.what());
        return nullptr;
    }
}

// 计算HRV指标
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_cmake_1project_1test_IndicatorCalculator_calculateHRVMetrics(
    JNIEnv* env, jobject thiz, jlong calculatorHandle, jobject rrIntervals) {
    try {
        if (calculatorHandle == 0) {
            __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Invalid calculator handle: 0");
            return nullptr;
        }
        
        MetricsCalculator* calculator = reinterpret_cast<MetricsCalculator*>(calculatorHandle);
        
        // 将Java的List<Float>转换为C++的vector<float>
        std::vector<float> cppRrIntervals = convertJavaFloatListToVector(env, rrIntervals);
        
        // 计算HRV指标
        std::map<std::string, float> metrics = calculator->calculate_all_hrv_metrics(cppRrIntervals);
        
        // 将C++的map转换为Java的Map
        jobject result = convertMetricsMapToJava(env, metrics);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "Successfully calculated HRV metrics, %zu metrics", metrics.size());
        return result;
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "Failed to calculate HRV metrics: %s", e.what());
        return nullptr;
    }
}

// ============================================================================
// 新增辅助函数实现
// ============================================================================

// 将C++的map<string, float>转换为Java的Map<String, Float>
jobject convertMetricsMapToJava(JNIEnv* env, const std::map<std::string, float>& metrics) {
    // 创建HashMap
    jclass hashMapClass = env->FindClass("java/util/HashMap");
    jmethodID hashMapConstructor = env->GetMethodID(hashMapClass, "<init>", "()V");
    jobject hashMap = env->NewObject(hashMapClass, hashMapConstructor);
    
    // 获取put方法
    jmethodID putMethod = env->GetMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
    
    // 获取Float类
    jclass floatClass = env->FindClass("java/lang/Float");
    jmethodID floatConstructor = env->GetMethodID(floatClass, "<init>", "(F)V");
    
    // 遍历C++ map并添加到Java HashMap
    for (const auto& pair : metrics) {
        // 创建Java String
        jstring key = env->NewStringUTF(pair.first.c_str());
        
        // 创建Java Float
        jobject value = env->NewObject(floatClass, floatConstructor, pair.second);
        
        // 添加到HashMap
        env->CallObjectMethod(hashMap, putMethod, key, value);
        
        // 释放局部引用
        env->DeleteLocalRef(key);
        env->DeleteLocalRef(value);
    }
    
    return hashMap;
}


