#include "cpp/data_mapper.h"
#include <iostream>
#include <cstring>
#include <map>
#include <android/log.h>

// 构造函数
Mapper::Mapper() {
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DataMapper instance created");
}

// 析构函数
Mapper::~Mapper() {
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DataMapper instance destroyed");
}

SensorData Mapper::DataMapper(SensorData& data)
{
    // 添加空指针检查
    if (data.channel_data.valueless_by_exception()) {
        throw std::runtime_error("Channel data is in invalid state");
    }
    
    SensorData data_mapped;
    data_mapped = data;
    
    // 添加调试信息
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== 开始数据映射 ===");
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "数据类型: %d", static_cast<int>(data_mapped.data_type));
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: 数据类型值 = %d", static_cast<int>(data_mapped.data_type));
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "数据类型详细: ");
    switch(data_mapped.data_type) {
        case DataType::EEG: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "EEG (0)"); break;
        case DataType::ECG_2LEAD: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "ECG_2LEAD (1)"); break;
        case DataType::ECG_12LEAD: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "ECG_12LEAD (2)"); break;
        case DataType::PPG: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "PPG (3)"); break;
        case DataType::RESPIRATION: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "RESPIRATION (4)"); break;
        case DataType::SNORE: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "SNORE (5)"); break;
        case DataType::STETHOSCOPE: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "STETHOSCOPE (6)"); break;
        case DataType::MIT_BIH: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "MIT_BIH (7)"); break;
        case DataType::PW_ECG_SL: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "PW_ECG_SL (8)"); break;
        default: __android_log_print(ANDROID_LOG_INFO, "DataMapper", "未知类型"); break;
    }
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "包序号: %d", data_mapped.packet_sn);
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "时间戳: %lld", data_mapped.timestamp);
    
    // 检查通道数据类型并安全处理
    try {
        switch(data_mapped.data_type){
            case DataType::EEG :
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用EEG数据映射器");
                data_mapped = EEG_Data_Mapper(data_mapped);break;
            case DataType::ECG_2LEAD:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用ECG_2LEAD数据映射器");
                data_mapped = ECG_2LEAD_Data_Mapper(data_mapped);break;
            case DataType::ECG_12LEAD:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用ECG_12LEAD数据映射器");
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: 确认进入ECG_12LEAD分支");
                data_mapped = ECG_12LEAD_Data_Mapper(data_mapped);
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: ECG_12LEAD映射完成");
                break;
            case DataType::PPG:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用PPG数据映射器");
                data_mapped = PPG_Data_Mapper(data_mapped);break;
            case DataType::RESPIRATION:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用RESPIRATION数据映射器");
                data_mapped = Respiration_Data_Mapper(data_mapped);break;
            case DataType::SNORE:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用SNORE数据映射器");
                data_mapped = Snore_Data_Mapper(data_mapped);break;
            case DataType::STETHOSCOPE:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "调用STETHOSCOPE数据映射器");
                data_mapped = Stethoscope_Data_Mapper(data_mapped);break;
            default:
                __android_log_print(ANDROID_LOG_INFO, "DataMapper", "未知数据类型，跳过映射");
                // 对于未知类型，直接返回原始数据
                break;
        }
        
        // 检查映射后的通道数量
        if (std::holds_alternative<std::vector<std::vector<float>>>(data_mapped.channel_data)) {
            auto& output_channels = std::get<std::vector<std::vector<float>>>(data_mapped.channel_data);
            __android_log_print(ANDROID_LOG_INFO, "DataMapper", "映射后通道数量: %zu", output_channels.size());
        } else if (std::holds_alternative<std::vector<float>>(data_mapped.channel_data)) {
            __android_log_print(ANDROID_LOG_INFO, "DataMapper", "映射后为单通道数据");
        }
        
    } catch (const std::exception& e) {
        // 如果映射失败，记录错误并返回原始数据
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Data mapping failed: %s", e.what());
        return data; // 返回原始数据而不是抛出异常
    }
    
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== 数据映射完成 ===");
    return data_mapped;
}

// EEG数据映射器 - 处理已解析的通道数据
SensorData Mapper::EEG_Data_Mapper(SensorData& data)
{
    SensorData processed = data;
    
    try {
        // 检查通道数据类型 - 支持多种格式
        if (std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
            // 多通道格式
            auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
            
            if (input_channels.empty()) {
                __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Input channel data for EEG is empty");
                return data; // 返回原始数据
            }
            
            // 创建输出通道数据
            std::vector<std::vector<float>> output_channels;
            output_channels.reserve(input_channels.size());
            
            // 复制并应用校准系数 (0.318 μV/unit)
            for (const auto& input_channel : input_channels) {
                std::vector<float> output_channel;
                output_channel.reserve(input_channel.size());
                
                for (float value : input_channel) {
                    output_channel.push_back(value * 0.318f); // 转换为μV
                }
                output_channels.push_back(output_channel);
            }
            
            // 更新处理后的通道数据
            processed.channel_data = output_channels;
            
        } else if (std::holds_alternative<std::vector<float>>(data.channel_data)) {
            // 单通道格式
            auto& input_channel = std::get<std::vector<float>>(data.channel_data);
            
            if (input_channel.empty()) {
                __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Input channel data for EEG is empty");
                return data; // 返回原始数据
            }
            
            // 创建输出通道数据
            std::vector<float> output_channel;
            output_channel.reserve(input_channel.size());
            
            // 应用校准系数
            for (float value : input_channel) {
                output_channel.push_back(value * 0.318f); // 转换为μV
            }
            
            // 更新处理后的通道数据
            processed.channel_data = output_channel;
            
        } else {
            __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Unknown channel data format for EEG");
            return data; // 返回原始数据
        }
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Error in EEG_Data_Mapper: %s", e.what());
        return data; // 返回原始数据
    }
    
    return processed;
}

// 胸腹设备数据映射器 - 处理已解析的通道数据
SensorData Mapper::ECG_2LEAD_Data_Mapper(SensorData& data) {
    SensorData processed = data;
    
    try {
        // 检查通道数据类型 - 支持多种格式
        if (std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
            // 多通道格式
            auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
            
            if (input_channels.empty()) {
                __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Input channel data for ECG_2LEAD is empty");
                return data; // 返回原始数据
            }
            
            // 创建输出通道数据
            std::vector<std::vector<float>> output_channels;
            output_channels.reserve(input_channels.size());
            
            // 复制并应用校准系数 (0.5 mV/unit)
            for (const auto& input_channel : input_channels) {
                std::vector<float> output_channel;
                output_channel.reserve(input_channel.size());
                
                for (float value : input_channel) {
                    output_channel.push_back(value * 0.5f); // 转换为mV
                }
                output_channels.push_back(output_channel);
            }
            
            // 更新处理后的通道数据
            processed.channel_data = output_channels;
            
        } else if (std::holds_alternative<std::vector<float>>(data.channel_data)) {
            // 单通道格式
            auto& input_channel = std::get<std::vector<float>>(data.channel_data);
            
            if (input_channel.empty()) {
                __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Input channel data for ECG_2LEAD is empty");
                return data; // 返回原始数据
            }
            
            // 创建输出通道数据
            std::vector<float> output_channel;
            output_channel.reserve(input_channel.size());
            
            // 应用校准系数
            for (float value : input_channel) {
                output_channel.push_back(value * 0.5f); // 转换为mV
            }
            
            // 更新处理后的通道数据
            processed.channel_data = output_channel;
            
        } else {
            __android_log_print(ANDROID_LOG_WARN, "DataMapper", "Warning: Unknown channel data format for ECG_2LEAD");
            return data; // 返回原始数据
        }
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "Error in ECG_2LEAD_Data_Mapper: %s", e.what());
        return data; // 返回原始数据
    }
    
    return processed;
}

// 12导联心电数据映射器 - 处理已解析的通道数据
SensorData Mapper::ECG_12LEAD_Data_Mapper(SensorData& data)
{
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== 开始ECG_12LEAD通道映射 ===");
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "数据类型: %d", static_cast<int>(data.data_type));
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "包序号: %d", data.packet_sn);
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "时间戳: %lld", data.timestamp);
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: ECG_12LEAD_Data_Mapper函数被调用");
    
    SensorData processed = data;
    
    try {
    
    // 检查通道数据类型
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "检查通道数据类型...");
    if (!std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "错误：通道数据格式不正确，期望std::vector<std::vector<float>>");
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "实际类型索引: %zu", data.channel_data.index());
        throw std::runtime_error("Invalid channel data format for ECG_12LEAD");
    }
    
    // 获取已解析的通道数据
    auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "输入通道数量: %zu", input_channels.size());
    
    // 检查输入通道是否为空
    if (input_channels.empty()) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "错误：输入通道数据为空");
        throw std::runtime_error("Input channel data for ECG_12LEAD is empty");
    }
    
    // 确保有足够的通道 (至少需要8个通道：V1, LA-RA, LL-RA, V2, V3, V4, V5, V6)
    if (input_channels.size() < 8) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "错误：输入通道数量不足，需要至少8个通道，实际只有 %zu 个", input_channels.size());
        throw std::runtime_error("Input channel data for ECG_12LEAD has less than 8 channels");
    }
    
    // 检查关键通道是否有数据
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "检查关键通道数据...");
    for (size_t i = 0; i < 8; ++i) {
        if (input_channels[i].empty()) {
            __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "错误：通道 %zu 为空", i);
            throw std::runtime_error("Channel " + std::to_string(i) + " for ECG_12LEAD is empty");
        }
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "通道 %zu 采样点数: %zu", i, input_channels[i].size());
    }
    
    // 获取采样点数
    size_t num_samples = input_channels[0].size();
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "基准采样点数: %zu", num_samples);
    
    // 验证所有关键通道都有相同的采样点数
    for (size_t i = 0; i < 8; ++i) {
        if (input_channels[i].size() != num_samples) {
            __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "错误：通道 %zu 采样点数不一致，期望 %zu，实际 %zu", 
                               i, num_samples, input_channels[i].size());
            throw std::runtime_error("Channel " + std::to_string(i) + " has different sample count: " + 
                                   std::to_string(input_channels[i].size()) + " vs " + std::to_string(num_samples));
        }
    }
    
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "数据验证通过，开始通道映射...");
    
    // 创建12导联输出结构，并初始化所有通道的大小
    std::vector<std::vector<float>> output_channels(12);
    for (int ch = 0; ch < 12; ++ch) {
        output_channels[ch].resize(num_samples, 0.0f); // 初始化为0
    }

    
    // 通道0: V1电极信号 (直接复制)
    output_channels[0] = input_channels[0];
    
    // 通道1: Lead I = LA - RA (直接复制)
    output_channels[1] = input_channels[1];
    
    // 通道2: Lead II = LL - RA (直接复制)
    output_channels[2] = input_channels[2];
    
    // 通道3: Lead III = LL - LA = Lead II - Lead I
    for (size_t sample = 0; sample < num_samples; ++sample) {
        output_channels[3][sample] = output_channels[2][sample] - output_channels[1][sample];
    }
    
    // 胸导联 V2-V6 (直接复制)
    output_channels[4] = input_channels[3];  // V2
    output_channels[5] = input_channels[4];  // V3
    output_channels[6] = input_channels[5];  // V4
    output_channels[7] = input_channels[6];  // V5
    output_channels[8] = input_channels[7];  // V6
    
    // 计算加压肢体导联 (aVR, aVL, aVF)
    // 根据用户提供的新公式：
    // aVR = -1/2 × (Lead I + Lead II)
    // aVL = -1/2 × (Lead I - Lead III)
    // aVF = -1/2 × (Lead II + Lead III)
    
    for (size_t sample = 0; sample < num_samples; ++sample) {
        float lead_I = output_channels[1][sample];   // Lead I = LA - RA
        float lead_II = output_channels[2][sample];  // Lead II = LL - RA
        float lead_III = output_channels[3][sample]; // Lead III = LL - LA
        
        // 使用新公式计算加压肢体导联
        output_channels[9][sample] = -0.5f * (lead_I + lead_II);  // aVR = -1/2 × (I + II)
        output_channels[10][sample] = -0.5f * (lead_I - lead_III); // aVL = -1/2 × (I - III)
        output_channels[11][sample] = -0.5f * (lead_II + lead_III); // aVF = -1/2 × (II + III)
    }
    
    // 验证输出通道的完整性
    for (size_t ch = 0; ch < output_channels.size(); ++ch) {
        if (output_channels[ch].size() != num_samples) {
            throw std::runtime_error("Output channel " + std::to_string(ch) + " has incorrect size: " + 
                                   std::to_string(output_channels[ch].size()) + " vs expected " + std::to_string(num_samples));
        }
    }
    
    // 更新处理后的通道数据
    processed.channel_data = output_channels;
    
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "ECG_12LEAD通道映射完成！");
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "输出通道数量: %zu", output_channels.size());
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "每个通道采样点数: %zu", num_samples);
    __android_log_print(ANDROID_LOG_INFO, "DataMapper", "=== ECG_12LEAD通道映射结束 ===");
    
    // 验证映射结果
    if (std::holds_alternative<std::vector<std::vector<float>>>(processed.channel_data)) {
        auto& final_channels = std::get<std::vector<std::vector<float>>>(processed.channel_data);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "最终验证 - 映射后通道数量: %zu", final_channels.size());
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "最终验证失败 - 通道数据类型错误");
    }
    
    return processed;
    
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "ECG_12LEAD映射异常: %s", e.what());
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "包序号: %d", data.packet_sn);
        __android_log_print(ANDROID_LOG_ERROR, "DataMapper", "返回原始数据（8通道）");
        return data; // 返回原始数据
    }
}

// PPG数据映射器 - 处理已解析的通道数据
SensorData Mapper::PPG_Data_Mapper(SensorData& data)
{
    SensorData processed = data;
    
    // 检查通道数据类型
    if (!std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
        throw std::runtime_error("Invalid channel data format for PPG");
    }
    
    // 获取已解析的通道数据
    auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
    
    // 检查输入通道是否为空
    if (input_channels.empty()) {
        throw std::runtime_error("Input channel data for PPG is empty");
    }
    
    // 确保有足够的通道
    if (input_channels.size() < 2) {
        throw std::runtime_error("Input channel data for PPG has less than 2 channels");
    }
    
    // 检查每个通道是否有数据
    for (size_t i = 0; i < 2; ++i) {
        if (input_channels[i].empty()) {
            throw std::runtime_error("Channel " + std::to_string(i) + " for PPG is empty");
        }
    }
    
    // 创建输出通道数据
    std::vector<std::vector<float>> output(2);
    
    // 通道0: 红光数据
    output[0] = input_channels[0];
    
    // 通道1: 红外光数据
    output[1] = input_channels[1];
    
    // 更新处理后的通道数据
    processed.channel_data = output;
    
    return processed;
}

// 呼吸数据映射器 - 处理已解析的通道数据
SensorData Mapper::Respiration_Data_Mapper(SensorData& data)
{
    SensorData processed = data;
    
    // 检查通道数据类型
    if (!std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
        throw std::runtime_error("Invalid channel data format for Respiration");
    }
    
    // 获取已解析的通道数据
    auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
    
    // 检查输入通道是否为空
    if (input_channels.empty()) {
        throw std::runtime_error("Input channel data for Respiration is empty");
    }
    
    // 确保有足够的通道
    if (input_channels.size() < 1) {
        throw std::runtime_error("Input channel data for Respiration has no channels");
    }
    
    // 检查第一个通道是否有数据
    if (input_channels[0].empty()) {
        throw std::runtime_error("Channel 0 for Respiration is empty");
    }
    
    // 创建输出通道数据
    std::vector<std::vector<float>> output(1);
    output[0] = input_channels[0];
    
    // 更新处理后的通道数据
    processed.channel_data = output;
    
    return processed;
}

// 打鼾数据映射器 - 处理已解析的通道数据
SensorData Mapper::Snore_Data_Mapper(SensorData& data)
{
    SensorData processed = data;
    
    // 检查通道数据类型
    if (!std::holds_alternative<std::vector<float>>(data.channel_data)) {
        throw std::runtime_error("Invalid channel data format for SNORE");
    }
    
    // 获取已解析的通道数据
    auto& raw_samples = std::get<std::vector<float>>(data.channel_data);
    
    // 检查输入数据是否为空
    if (raw_samples.empty()) {
        throw std::runtime_error("Input channel data for SNORE is empty");
    }
    
    // 应用校准系数 (0.146 mV/unit)
    std::vector<float> calibrated;
    calibrated.reserve(raw_samples.size());
    
    for (float sample : raw_samples) {
        calibrated.push_back(sample * 0.146f);
    }
    
    // 更新处理后的通道数据
    processed.channel_data = calibrated;
    
    return processed;
}

// 听诊器数据映射器 - 处理已解析的通道数据
SensorData Mapper::Stethoscope_Data_Mapper(SensorData& data)
{
    SensorData processed = data;
    
    // 检查通道数据类型
    if (!std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
        throw std::runtime_error("Invalid channel data format for Stethoscope");
    }
    
    // 获取已解析的通道数据
    auto& input_channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
    
    // 检查输入通道是否为空
    if (input_channels.empty()) {
        throw std::runtime_error("Input channel data for Stethoscope is empty");
    }
    
    // 确保有足够的通道
    if (input_channels.size() < 2) {
        throw std::runtime_error("Input channel data for Stethoscope has less than 2 channels");
    }
    
    // 检查每个通道是否有数据
    for (size_t i = 0; i < 2; ++i) {
        if (input_channels[i].empty()) {
            throw std::runtime_error("Channel " + std::to_string(i) + " for Stethoscope is empty");
        }
    }
    
    // 创建输出通道数据
    std::vector<std::vector<float>> output(2);
    output[0] = input_channels[0];
    output[1] = input_channels[1];
    
    // 更新处理后的通道数据
    processed.channel_data = output;
    
    return processed;
}

// End of data_mapper.cpp

