// metrics_calculator.cpp
#include "cpp/indicator_cal.h"
#include <cmath>
#include <algorithm>
#include <numeric>
#include <complex>
#include <iostream>

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

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

// 完整数据处理流程
std::map<std::string, float> MetricsCalculator::process_complete_pipeline(const SensorData& raw_data, float sample_rate) {
    std::map<std::string, float> all_metrics;
    
    __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "开始完整数据处理流程");
    __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "数据类型: %d, 采样率: %.2f Hz", static_cast<int>(raw_data.data_type), sample_rate);
    
    try {
        // 根据数据类型计算相应的指标
        switch (raw_data.data_type) {
            case DataType::ECG_2LEAD:
            case DataType::ECG_12LEAD: {
                __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "处理ECG数据");
                auto ecg_metrics = calculate_all_ecg_metrics(raw_data, sample_rate);
                all_metrics.insert(ecg_metrics.begin(), ecg_metrics.end());
                break;
            }
            case DataType::PPG: {
                __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "处理PPG数据");
                auto ppg_metrics = calculate_all_ppg_metrics(raw_data, sample_rate);
                all_metrics.insert(ppg_metrics.begin(), ppg_metrics.end());
                break;
            }
            case DataType::EEG: {
                __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "处理EEG数据");
                // 获取单通道数据
                std::vector<float> signal;
                if (std::holds_alternative<std::vector<float>>(raw_data.channel_data)) {
                    signal = std::get<std::vector<float>>(raw_data.channel_data);
                } else {
                    const auto& channels = std::get<std::vector<std::vector<float>>>(raw_data.channel_data);
                    if (!channels.empty()) {
                        signal = channels[0];
                    }
                }
                
                if (!signal.empty()) {
                    all_metrics["signal_quality"] = calculate_signal_quality(signal);
                    all_metrics["mean"] = std::accumulate(signal.begin(), signal.end(), 0.0f) / signal.size();
                    all_metrics["std_dev"] = std::sqrt(std::accumulate(signal.begin(), signal.end(), 0.0f, 
                        [&](float acc, float val) { return acc + (val - all_metrics["mean"]) * (val - all_metrics["mean"]); }) / signal.size());
                }
                break;
            }
            case DataType::RESPIRATION: {
                __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "处理呼吸数据");
                // 获取单通道数据
                std::vector<float> signal;
                if (std::holds_alternative<std::vector<float>>(raw_data.channel_data)) {
                    signal = std::get<std::vector<float>>(raw_data.channel_data);
                } else {
                    const auto& channels = std::get<std::vector<std::vector<float>>>(raw_data.channel_data);
                    if (!channels.empty()) {
                        signal = channels[0];
                    }
                }
                
                if (!signal.empty()) {
                    all_metrics["signal_quality"] = calculate_signal_quality(signal);
                    all_metrics["mean"] = std::accumulate(signal.begin(), signal.end(), 0.0f) / signal.size();
                    all_metrics["peak_to_peak"] = *std::max_element(signal.begin(), signal.end()) - *std::min_element(signal.begin(), signal.end());
                }
                break;
            }
            default: {
                __android_log_print(ANDROID_LOG_WARN, "IndicatorCalculator", "未知数据类型: %d", static_cast<int>(raw_data.data_type));
                // 获取单通道数据
                std::vector<float> signal;
                if (std::holds_alternative<std::vector<float>>(raw_data.channel_data)) {
                    signal = std::get<std::vector<float>>(raw_data.channel_data);
                } else {
                    const auto& channels = std::get<std::vector<std::vector<float>>>(raw_data.channel_data);
                    if (!channels.empty()) {
                        signal = channels[0];
                    }
                }
                
                if (!signal.empty()) {
                    all_metrics["signal_quality"] = calculate_signal_quality(signal);
                }
                break;
            }
        }
        
        // 添加通用指标
        all_metrics["data_type"] = static_cast<float>(raw_data.data_type);
        all_metrics["sample_rate"] = sample_rate;
        all_metrics["timestamp"] = static_cast<float>(raw_data.timestamp);
        all_metrics["packet_sn"] = static_cast<float>(raw_data.packet_sn);
        
        __android_log_print(ANDROID_LOG_INFO, "IndicatorCalculator", "完整数据处理流程完成，计算了 %zu 个指标", all_metrics.size());
        
    } catch (const std::exception& e) {
        __android_log_print(ANDROID_LOG_ERROR, "IndicatorCalculator", "数据处理流程异常: %s", e.what());
        all_metrics["error"] = 1.0f;
        all_metrics["error_message"] = 0.0f; // 这里可以编码错误信息
    }
    
    return all_metrics;
}

// 自定义clamp函数，替代std::clamp（C++17特性）
template<typename T>
T clamp(T value, T min_val, T max_val) {
    if (value < min_val) return min_val;
    if (value > max_val) return max_val;
    return value;
}

// 辅助函数：从SensorData获取单通道数据
static const std::vector<float>& get_single_channel(const SensorData& data) {
    if (std::holds_alternative<std::vector<float>>(data.channel_data)) {
        return std::get<std::vector<float>>(data.channel_data);
    } else {
        const auto& channels = std::get<std::vector<std::vector<float>>>(data.channel_data);
        if (!channels.empty()) {
            // 对于十二导联心电，优先选择II导联（通道2）
            if (data.data_type == DataType::ECG_12LEAD && channels.size() > 2) {
                return channels[2]; // 返回II导联（通道2）
            } else if (data.data_type == DataType::ECG_12LEAD && channels.size() > 1) {
                return channels[1]; // 备选：通道1
            } else {
                return channels[0]; // 返回第一通道
            }
        }
        static const std::vector<float> empty;
        return empty;
    }
}

// 辅助函数：从SensorData获取多通道数据
static const std::vector<std::vector<float>>& get_multi_channel(const SensorData& data) {
    if (std::holds_alternative<std::vector<std::vector<float>>>(data.channel_data)) {
        return std::get<std::vector<std::vector<float>>>(data.channel_data);
    } else {
        static const std::vector<std::vector<float>> empty;
        return empty;
    }
}

// 辅助函数：计算分位数（q 取值范围 0.0-1.0）
static float compute_percentile(const std::vector<float>& data, float q) {
    if (data.empty()) return 0.0f;
    float qq = q;
    if (qq < 0.0f) qq = 0.0f;
    if (qq > 1.0f) qq = 1.0f;
    std::vector<float> sorted = data;
    std::sort(sorted.begin(), sorted.end());
    if (sorted.size() == 1) return sorted[0];
    float pos = qq * (sorted.size() - 1);
    size_t idx_low = static_cast<size_t>(std::floor(pos));
    size_t idx_high = static_cast<size_t>(std::ceil(pos));
    if (idx_low == idx_high) return sorted[idx_low];
    float w = pos - idx_low;
    return sorted[idx_low] * (1.0f - w) + sorted[idx_high] * w;
}

// 辅助函数：稳健估计AC/DC（使用分位数和中位数，抗异常）
static std::pair<float, float> robust_ac_dc(const std::vector<float>& signal) {
    if (signal.size() < 5) return {0.0f, 0.0f};
    // 使用5%-95%分位点估计幅度，使用中位数估计直流
    float p5 = compute_percentile(signal, 0.05f);
    float p95 = compute_percentile(signal, 0.95f);
    float median = compute_percentile(signal, 0.50f);
    float ac = (p95 - p5) * 0.5f;
    float dc = median;
    return {ac, dc};
}

// ECG心率计算 - 改进版本
float MetricsCalculator::calculate_heart_rate_ecg(const SensorData& ecg_signal, float sample_rate) {
    // 增强的输入验证
    if (sample_rate <= 0.0f || sample_rate > 10000.0f) {
        std::cerr << "警告: 采样率超出合理范围: " << sample_rate << "Hz" << std::endl;
        return 0.0f;
    }
    
    const auto& signal = get_single_channel(ecg_signal);
    
    // 确认通道选择
    if (ecg_signal.data_type == DataType::ECG_12LEAD) {
        if (std::holds_alternative<std::vector<std::vector<float>>>(ecg_signal.channel_data)) {
            const auto& channels = std::get<std::vector<std::vector<float>>>(ecg_signal.channel_data);
            __android_log_print(ANDROID_LOG_INFO, "HeartRate", "十二导联心电，总通道数: %zu", channels.size());
            if (channels.size() > 2) {
                __android_log_print(ANDROID_LOG_INFO, "HeartRate", "选择II导联（通道2）进行心率计算");
            } else if (channels.size() > 1) {
                __android_log_print(ANDROID_LOG_INFO, "HeartRate", "选择通道1作为备选");
            } else {
                __android_log_print(ANDROID_LOG_INFO, "HeartRate", "选择通道0");
            }
        }
    }
    
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "ECG信号长度: %zu, 采样率: %.1f Hz", signal.size(), sample_rate);
    
    // 对于十二导联心电，降低最小数据长度要求
    float min_samples = (ecg_signal.data_type == DataType::ECG_12LEAD) ? 
                       sample_rate * 0.2f : // 十二导联：0.2秒
                       sample_rate * 0.3f;   // 其他：0.3秒
    
    if (signal.size() < static_cast<size_t>(min_samples)) {
        __android_log_print(ANDROID_LOG_WARN, "HeartRate", "信号长度不足，需要至少 %.0f 个样本，实际 %zu", min_samples, signal.size());
        return 0.0f;
    }
    
    if (signal.size() < 3) {
        std::cerr << "警告: 信号样本数过少: " << signal.size() << std::endl;
        return 0.0f;
    }
    
    // 检测R峰
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "开始R峰检测...");
    auto r_peaks = detect_r_peaks(signal, sample_rate);
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "检测到 %zu 个R峰", r_peaks.size());
    
    // 输出R峰位置信息
    for (size_t i = 0; i < r_peaks.size(); i++) {
        __android_log_print(ANDROID_LOG_INFO, "HeartRate", "R峰 %zu: 位置=%.1f, 时间=%.3fs", 
                           i, r_peaks[i], r_peaks[i] / sample_rate);
    }
    
    if (r_peaks.size() < 1) {
        __android_log_print(ANDROID_LOG_WARN, "HeartRate", "检测到的R峰数量不足: %zu，至少需要1个", r_peaks.size());
        
        // 对于十二导联心电，尝试使用频率分析方法
        if (ecg_signal.data_type == DataType::ECG_12LEAD) {
            __android_log_print(ANDROID_LOG_INFO, "HeartRate", "尝试使用频率分析方法...");
            float estimated_hr = estimate_heart_rate_from_frequency(signal, sample_rate);
            if (estimated_hr > 0.0f) {
                __android_log_print(ANDROID_LOG_INFO, "HeartRate", "频率分析成功，心率: %.1f bpm", estimated_hr);
                return estimated_hr;
            }
        }
        
        return 0.0f;
    }
    
    // 如果只有一个R峰，使用时间窗口估算心率
    if (r_peaks.size() == 1) {
        float signal_duration = signal.size() / sample_rate; // 信号持续时间（秒）
        if (signal_duration > 0.5f) { // 至少0.5秒数据
            float estimated_hr = 60.0f / signal_duration; // 估算心率
            if (estimated_hr >= 30.0f && estimated_hr <= 300.0f) {
                return estimated_hr;
            }
        }
        return 0.0f;
    }
    
    // 计算RR间期
    std::vector<float> rr_intervals;
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "开始计算RR间期，R峰数量: %zu", r_peaks.size());
    
    for (size_t i = 1; i < r_peaks.size(); i++) {
        float rr = (r_peaks[i] - r_peaks[i-1]) / sample_rate; // 转换为秒
        __android_log_print(ANDROID_LOG_INFO, "HeartRate", "RR间期 %zu: %.3f秒 (%.1fms)", i, rr, rr * 1000.0f);
        
        if (rr > 0.2f && rr < 3.0f) { // 过滤异常值 (200ms-3s)
            rr_intervals.push_back(rr);
            __android_log_print(ANDROID_LOG_INFO, "HeartRate", "RR间期 %zu 有效", i);
        } else {
            __android_log_print(ANDROID_LOG_WARN, "HeartRate", "过滤异常RR间期: %.3f秒 (%.1fms)", rr, rr * 1000.0f);
        }
    }
    
    if (rr_intervals.empty()) {
        std::cerr << "警告: 所有RR间期都被过滤，无法计算心率" << std::endl;
        return 0.0f;
    }
    
    // 计算平均RR间期
    float avg_rr = std::accumulate(rr_intervals.begin(), rr_intervals.end(), 0.0f) / rr_intervals.size();
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "平均RR间期: %.3f秒 (%.1fms)", avg_rr, avg_rr * 1000.0f);
    
    // 转换为心率 (次/分钟)
    float heart_rate = 60.0f / avg_rr;
    __android_log_print(ANDROID_LOG_INFO, "HeartRate", "计算的心率: %.1f bpm", heart_rate);
    
    // 验证心率合理性
    if (heart_rate < 30.0f || heart_rate > 300.0f) {
        std::cerr << "警告: 计算的心率超出正常范围: " << heart_rate << " bpm" << std::endl;
        
        // 尝试使用简化的频率分析方法
        float estimated_hr = estimate_heart_rate_from_frequency(signal, sample_rate);
        if (estimated_hr > 0.0f) {
            std::cerr << "使用频率分析方法估算心率: " << estimated_hr << " bpm" << std::endl;
            return estimated_hr;
        }
        
        return 0.0f;
    }
    
    return heart_rate;
}

// 简化的频率分析心率估算方法
float MetricsCalculator::estimate_heart_rate_from_frequency(const std::vector<float>& signal, float sample_rate) {
    if (signal.size() < 50) return 0.0f; // 至少需要50个样本
    
    // 计算信号的功率谱密度
    std::vector<float> power_spectrum;
    const size_t fft_size = 256; // FFT大小
    
    // 简单的FFT实现（使用FFTW库或自实现）
    std::vector<std::complex<float>> fft_data(fft_size, 0.0f);
    
    // 填充数据
    for (size_t i = 0; i < std::min(signal.size(), fft_size); i++) {
        fft_data[i] = std::complex<float>(signal[i], 0.0f);
    }
    
    // 应用汉宁窗
    for (size_t i = 0; i < fft_size; i++) {
        float window = 0.5f * (1.0f - std::cos(2.0f * M_PI * i / (fft_size - 1)));
        fft_data[i] *= window;
    }
    
    // 简化的FFT计算（这里使用简化版本）
    std::vector<float> magnitude(fft_size / 2);
    for (size_t k = 0; k < fft_size / 2; k++) {
        std::complex<float> sum(0.0f, 0.0f);
        for (size_t n = 0; n < fft_size; n++) {
            float angle = -2.0f * M_PI * k * n / fft_size;
            sum += fft_data[n] * std::complex<float>(std::cos(angle), std::sin(angle));
        }
        magnitude[k] = std::abs(sum);
    }
    
    // 寻找心率频段的峰值 (0.8-3Hz, 对应48-180bpm)
    size_t low_bin = static_cast<size_t>(0.8f * fft_size / sample_rate);
    size_t high_bin = static_cast<size_t>(3.0f * fft_size / sample_rate);
    
    if (low_bin >= magnitude.size() || high_bin >= magnitude.size()) {
        return 0.0f;
    }
    
    // 寻找最大峰值
    size_t max_bin = low_bin;
    for (size_t i = low_bin; i <= high_bin && i < magnitude.size(); i++) {
        if (magnitude[i] > magnitude[max_bin]) {
            max_bin = i;
        }
    }
    
    // 计算对应的频率和心率
    float frequency = max_bin * sample_rate / fft_size;
    float heart_rate = frequency * 60.0f; // 转换为bpm
    
    // 验证心率合理性
    if (heart_rate >= 30.0f && heart_rate <= 300.0f) {
        return heart_rate;
    }
    
    return 0.0f;
}

// T波振幅计算 - 改进版本
float MetricsCalculator::calculate_t_wave_amplitude(const std::vector<float>& ecg_signal) {
    if (ecg_signal.empty()) return 0.0f;
    
    // 使用自适应窗口寻找T波
    const size_t n = ecg_signal.size();
    const size_t qrs_end = static_cast<size_t>(n * 0.25f); // QRS结束位置估计
    const size_t t_end = static_cast<size_t>(n * 0.6f);    // T波结束位置估计
    
    float max_amplitude = 0.0f;
    size_t t_peak_pos = qrs_end;
    
    // 在T波窗口内寻找最大振幅
    for (size_t i = qrs_end; i < t_end && i < n; i++) {
        if (std::abs(ecg_signal[i]) > max_amplitude) {
            max_amplitude = std::abs(ecg_signal[i]);
            t_peak_pos = i;
        }
    }
    
    // 计算T波相对于基线的振幅
    float baseline = 0.0f;
    const size_t baseline_start = std::max(size_t(0), t_peak_pos - static_cast<size_t>(0.1f * n));
    const size_t baseline_end = std::min(n - 1, t_peak_pos + static_cast<size_t>(0.1f * n));
    
    for (size_t i = baseline_start; i <= baseline_end; i++) {
        baseline += ecg_signal[i];
    }
    baseline /= (baseline_end - baseline_start + 1);
    
    return ecg_signal[t_peak_pos] - baseline;
}

// 新增：QRS宽度计算
float MetricsCalculator::calculate_qrs_width(const std::vector<float>& ecg_signal, float sample_rate) {
    if (ecg_signal.empty() || sample_rate <= 0) return 0.0f;
    
    // 检测R峰
    auto r_peaks = detect_r_peaks(ecg_signal, sample_rate);
    if (r_peaks.empty()) return 0.0f;
    
    float total_width = 0.0f;
    int valid_peaks = 0;
    
    for (float r_peak : r_peaks) {
        size_t r_idx = static_cast<size_t>(r_peak);
        if (r_idx >= ecg_signal.size()) continue;
        
        // 向前搜索Q波起点 (信号下降超过阈值的点)
        size_t q_start = r_idx;
        float threshold = 0.3f * std::abs(ecg_signal[r_idx]);
        
        for (int i = 0; i < static_cast<int>(0.1f * sample_rate) && q_start > 0; i++) {
            if (std::abs(ecg_signal[q_start] - ecg_signal[q_start - 1]) > threshold) {
                break;
            }
            q_start--;
        }
        
        // 向后搜索S波终点 (信号下降超过阈值的点)
        size_t s_end = r_idx;
        for (int i = 0; i < static_cast<int>(0.1f * sample_rate) && s_end < ecg_signal.size() - 1; i++) {
            if (std::abs(ecg_signal[s_end] - ecg_signal[s_end + 1]) > threshold) {
                break;
            }
            s_end++;
        }
        
        float width = static_cast<float>(s_end - q_start) / sample_rate * 1000.0f; // 转换为毫秒
        if (width > 40.0f && width < 200.0f) { // 正常QRS宽度范围
            total_width += width;
            valid_peaks++;
        }
    }
    
    return valid_peaks > 0 ? total_width / valid_peaks : 0.0f;
}

// 新增：ST段偏移计算
float MetricsCalculator::calculate_st_offset(const std::vector<float>& ecg_signal, float sample_rate) {
    if (ecg_signal.empty() || sample_rate <= 0) return 0.0f;
    
    // 检测R峰
    auto r_peaks = detect_r_peaks(ecg_signal, sample_rate);
    if (r_peaks.empty()) return 0.0f;
    
    float total_offset = 0.0f;
    int valid_peaks = 0;
    
    for (float r_peak : r_peaks) {
        size_t r_idx = static_cast<size_t>(r_peak);
        if (r_idx >= ecg_signal.size()) continue;
        
        // ST段位置：R峰后80ms
        size_t st_pos = r_idx + static_cast<size_t>(0.08f * sample_rate);
        if (st_pos >= ecg_signal.size()) continue;
        
        // 计算基线 (使用R峰前50ms的平均值)
        size_t baseline_start = std::max(size_t(0), r_idx - static_cast<size_t>(0.05f * sample_rate));
        float baseline = 0.0f;
        int baseline_count = 0;
        
        for (size_t i = baseline_start; i < r_idx; i++) {
            baseline += ecg_signal[i];
            baseline_count++;
        }
        
        if (baseline_count > 0) {
            baseline /= baseline_count;
            float st_offset = ecg_signal[st_pos] - baseline;
            total_offset += st_offset;
            valid_peaks++;
        }
    }
    
    return valid_peaks > 0 ? total_offset / valid_peaks : 0.0f;
}

// PPG心率计算 - 改进版本
float MetricsCalculator::calculate_heart_rate_ppg(const std::vector<float>& ppg_signal, float sample_rate) {
    // 增强的输入验证
    if (sample_rate <= 0.0f || sample_rate > 10000.0f) {
        std::cerr << "警告: PPG采样率超出合理范围: " << sample_rate << "Hz" << std::endl;
        return 0.0f;
    }
    
    if (ppg_signal.size() < static_cast<size_t>(sample_rate * 0.5f)) {
        std::cerr << "警告: PPG信号长度不足，至少需要 " << sample_rate * 0.5f << " 个样本" << std::endl;
        return 0.0f;
    }
    
    if (ppg_signal.size() < 3) {
        std::cerr << "警告: PPG信号样本数过少: " << ppg_signal.size() << std::endl;
        return 0.0f;
    }
    
    // 检测脉搏波峰
    auto pulse_peaks = detect_pulse_peaks(ppg_signal, sample_rate);
    if (pulse_peaks.size() < 2) {
        std::cerr << "警告: 检测到的脉搏波峰数量不足: " << pulse_peaks.size() << "，至少需要2个" << std::endl;
        return 0.0f;
    }
    
    // 计算脉搏间期
    std::vector<float> pulse_intervals;
    for (size_t i = 1; i < pulse_peaks.size(); i++) {
        float interval = (pulse_peaks[i] - pulse_peaks[i-1]) / sample_rate; // 转换为秒
        if (interval > 0.3f && interval < 3.0f) { // 过滤异常值 (300ms-3s)
            pulse_intervals.push_back(interval);
        } else {
            std::cerr << "警告: 过滤异常脉搏间期: " << interval * 1000.0f << "ms" << std::endl;
        }
    }
    
    if (pulse_intervals.empty()) {
        std::cerr << "警告: 所有脉搏间期都被过滤，无法计算心率" << std::endl;
        return 0.0f;
    }
    
    // 计算平均脉搏间期
    float avg_interval = std::accumulate(pulse_intervals.begin(), pulse_intervals.end(), 0.0f) / pulse_intervals.size();
    
    // 转换为心率 (次/分钟)
    float heart_rate = 60.0f / avg_interval;
    
    // 验证心率合理性
    if (heart_rate < 30.0f || heart_rate > 300.0f) {
        std::cerr << "警告: 计算的PPG心率超出正常范围: " << heart_rate << " bpm" << std::endl;
        return 0.0f;
    }
    
    return heart_rate;
}

// 血氧饱和度计算 - 改进版本
float MetricsCalculator::calculate_spo2(const SensorData& ppg_data) {
    // 输入验证
    if (!std::holds_alternative<std::vector<std::vector<float>>>(ppg_data.channel_data)) {
        std::cerr << "警告: PPG数据格式不正确，需要多通道数据" << std::endl;
        return 0.0f;
    }
    
    const auto& channels = std::get<std::vector<std::vector<float>>>(ppg_data.channel_data);
    if (channels.size() < 2) {
        std::cerr << "警告: PPG数据通道数不足，需要至少2个通道，当前: " << channels.size() << std::endl;
        return 0.0f;
    }
    
    const auto& red_channel = channels[0];
    const auto& ir_channel = channels[1];
    
    if (red_channel.empty() || ir_channel.empty()) {
        std::cerr << "警告: 红光或红外光通道数据为空" << std::endl;
        return 0.0f;
    }
    
    if (red_channel.size() != ir_channel.size()) {
        std::cerr << "警告: 红光和红外光通道长度不一致: " << red_channel.size() << " vs " << ir_channel.size() << std::endl;
        return 0.0f;
    }
    
    // 轻量级异常值裁剪：将数据裁剪到1%-99%范围，提高稳健性
    auto clipped_copy = [](const std::vector<float>& src) {
        std::vector<float> out = src;
        if (out.size() >= 5) {
            float p1 = compute_percentile(out, 0.01f);
            float p99 = compute_percentile(out, 0.99f);
            for (float& v : out) {
                if (v < p1) v = p1;
                else if (v > p99) v = p99;
            }
        }
        return out;
    };

    std::vector<float> red_clipped = clipped_copy(red_channel);
    std::vector<float> ir_clipped = clipped_copy(ir_channel);

    // 稳健估计红光和红外光的AC/DC分量
    auto [red_ac, red_dc] = robust_ac_dc(red_clipped);
    auto [ir_ac, ir_dc] = robust_ac_dc(ir_clipped);
    
    // 防止除零和异常值
    if (std::abs(red_dc) < 0.0001f || std::abs(ir_dc) < 0.0001f) {
        std::cerr << "警告: 直流分量过小，红光: " << red_dc << ", 红外光: " << ir_dc << std::endl;
        return 0.0f;
    }
    
    if (std::abs(red_ac) < 0.0001f || std::abs(ir_ac) < 0.0001f) {
        std::cerr << "警告: 交流分量过小，红光: " << red_ac << ", 红外光: " << ir_ac << std::endl;
        return 0.0f;
    }
    
    // 计算R值 (红光AC/DC与红外光AC/DC的比值)
    float r_value = (red_ac / red_dc) / (ir_ac / ir_dc);
    
    // 验证R值合理性
    if (std::abs(r_value) < 0.1f || std::abs(r_value) > 10.0f) {
        std::cerr << "警告: R值超出合理范围: " << r_value << std::endl;
        return 0.0f;
    }
    float spo2;
    // 采用常用经验线性映射：SpO2 = 110 - 25 * R （需设备校准）
    if(r_value>0)  spo2 = 110.0f - 25.0f * r_value;
    else  spo2 = 110.0f + 25.0f * r_value;

    // 限制在合理范围内 (70% - 100%)
    spo2 = clamp(spo2, 70.0f, 100.0f);
    
    return spo2;
}

// 新增：灌注指数计算 (PI - Perfusion Index)
float MetricsCalculator::calculate_perfusion_index(const SensorData& ppg_data) {
    if (!std::holds_alternative<std::vector<std::vector<float>>>(ppg_data.channel_data) || 
        std::get<std::vector<std::vector<float>>>(ppg_data.channel_data).size() < 1) {
        return 0.0f;
    }
    
    const auto& channels = std::get<std::vector<std::vector<float>>>(ppg_data.channel_data);
    const auto& signal = channels[0]; // 使用第一通道
    
    if (signal.empty()) return 0.0f;
    
    // 计算AC和DC分量
    float max_val = *std::max_element(signal.begin(), signal.end());
    float min_val = *std::min_element(signal.begin(), signal.end());
    float dc = (max_val + min_val) / 2.0f;
    float ac = (max_val - min_val) / 2.0f;
    
    // 灌注指数 = (AC / DC) * 100%
    if (dc < 0.0001f) return 0.0f;
    return (ac / dc) * 100.0f;
}

// 脉搏波宽度计算 - 改进版本
float MetricsCalculator::calculate_pulse_width(const std::vector<float>& ppg_signal) {
    if (ppg_signal.empty()) return 0.0f;
    
    // 找到最大峰值位置
    auto max_it = std::max_element(ppg_signal.begin(), ppg_signal.end());
    size_t peak_idx = std::distance(ppg_signal.begin(), max_it);
    float peak_value = *max_it;
    
    // 自适应阈值
    float threshold = 0.1f * peak_value;
    
    // 找到上升沿起点 (信号值小于阈值的点)
    size_t start_idx = peak_idx;
    while (start_idx > 0 && ppg_signal[start_idx] > threshold) {
        start_idx--;
    }
    
    // 找到下降沿终点 (信号值小于阈值的点)
    size_t end_idx = peak_idx;
    while (end_idx < ppg_signal.size() - 1 && ppg_signal[end_idx] > threshold) {
        end_idx++;
    }
    
    return static_cast<float>(end_idx - start_idx);
}

// 红光/红外光振幅比 - 改进版本
float MetricsCalculator::calculate_amplitude_ratio(const SensorData& ppg_data) {
    if (!std::holds_alternative<std::vector<std::vector<float>>>(ppg_data.channel_data) || 
        std::get<std::vector<std::vector<float>>>(ppg_data.channel_data).size() < 2) {
        return 0.0f;
    }
    
    const auto& channels = std::get<std::vector<std::vector<float>>>(ppg_data.channel_data);
    const auto& red_channel = channels[0];
    const auto& ir_channel = channels[1]; 
    
    if (red_channel.empty() || ir_channel.empty()) return 0.0f;
    
    // 计算红光和红外光的峰峰值
    float red_amp = *std::max_element(red_channel.begin(), red_channel.end()) - 
                   *std::min_element(red_channel.begin(), red_channel.end());
    
    float ir_amp = *std::max_element(ir_channel.begin(), ir_channel.end()) - 
                  *std::min_element(ir_channel.begin(), ir_channel.end());
    
    // 防止除零
    if (ir_amp < 0.0001f) return 0.0f;
    
    return red_amp / ir_amp;
}

// HRV指标 - SDNN (RR间期的标准差) - 改进版本
float MetricsCalculator::calculate_sdnn(const std::vector<float>& rr_intervals) {
    if (rr_intervals.size() < 2) return 0.0f;
    
    // 过滤异常RR间期
    std::vector<float> filtered_rr;
    for (float rr : rr_intervals) {
        if (rr > 0.2f && rr < 3.0f) { // 200ms-3s范围
            filtered_rr.push_back(rr);
        }
    }
    
    if (filtered_rr.size() < 2) return 0.0f;
    
    float mean = std::accumulate(filtered_rr.begin(), filtered_rr.end(), 0.0f) / filtered_rr.size();
    
    float variance = 0.0f;
    for (float rr : filtered_rr) {
        variance += (rr - mean) * (rr - mean);
    }
    variance /= filtered_rr.size();
    
    return std::sqrt(variance);
}

// HRV指标 - RMSSD (相邻RR间期差值的均方根) - 改进版本
float MetricsCalculator::calculate_rmssd(const std::vector<float>& rr_intervals) {
    if (rr_intervals.size() < 2) return 0.0f;
    
    // 过滤异常RR间期
    std::vector<float> filtered_rr;
    for (float rr : rr_intervals) {
        if (rr > 0.2f && rr < 3.0f) { // 200ms-3s范围
            filtered_rr.push_back(rr);
        }
    }
    
    if (filtered_rr.size() < 2) return 0.0f;
    
    float sum_sq_diff = 0.0f;
    for (size_t i = 1; i < filtered_rr.size(); i++) {
        float diff = filtered_rr[i] - filtered_rr[i-1];
        sum_sq_diff += diff * diff;
    }
    
    return std::sqrt(sum_sq_diff / (filtered_rr.size() - 1));
}

// 新增：HRV指标 - pNN50 (相邻RR间期差值>50ms的比例)
float MetricsCalculator::calculate_pnn50(const std::vector<float>& rr_intervals) {
    if (rr_intervals.size() < 2) return 0.0f;
    
    // 过滤异常RR间期
    std::vector<float> filtered_rr;
    for (float rr : rr_intervals) {
        if (rr > 0.2f && rr < 3.0f) { // 200ms-3s范围
            filtered_rr.push_back(rr);
        }
    }
    
    if (filtered_rr.size() < 2) return 0.0f;
    
    int count_50ms = 0;
    for (size_t i = 1; i < filtered_rr.size(); i++) {
        float diff = std::abs(filtered_rr[i] - filtered_rr[i-1]);
        if (diff > 0.05f) { // 50ms
            count_50ms++;
        }
    }
    
    return static_cast<float>(count_50ms) / (filtered_rr.size() - 1) * 100.0f;
}

// 新增：HRV指标 - 三角指数
float MetricsCalculator::calculate_triangular_index(const std::vector<float>& rr_intervals) {
    if (rr_intervals.size() < 10) return 0.0f;
    
    // 过滤异常RR间期
    std::vector<float> filtered_rr;
    for (float rr : rr_intervals) {
        if (rr > 0.2f && rr < 3.0f) { // 200ms-3s范围
            filtered_rr.push_back(rr);
        }
    }
    
    if (filtered_rr.size() < 10) return 0.0f;
    
    // 创建直方图
    const int bins = 256;
    std::vector<int> histogram(bins, 0);
    
    float min_rr = *std::min_element(filtered_rr.begin(), filtered_rr.end());
    float max_rr = *std::max_element(filtered_rr.begin(), filtered_rr.end());
    float bin_width = (max_rr - min_rr) / bins;
    
    if (bin_width < 0.001f) return 0.0f; // 防止除零
    
    for (float rr : filtered_rr) {
        int bin = static_cast<int>((rr - min_rr) / bin_width);
        if (bin >= 0 && bin < bins) {
            histogram[bin]++;
        }
    }
    
    // 找到直方图最大值
    int max_count = *std::max_element(histogram.begin(), histogram.end());
    if (max_count == 0) return 0.0f;
    
    // 计算三角指数
    return static_cast<float>(filtered_rr.size()) / max_count;
}

// 改进的R峰检测算法 (基于Pan-Tompkins算法)
std::vector<float> MetricsCalculator::detect_r_peaks(const std::vector<float>& ecg_signal, float sample_rate) {
    std::vector<float> r_peaks;
    if (ecg_signal.size() < 5 || sample_rate <= 0) return r_peaks;
    
    const size_t n = ecg_signal.size();
    
    // 1. 计算积分窗口大小 (150ms窗口)
    const int win_integ = static_cast<int>(0.15f * sample_rate + 0.5f); // 四舍五入
    if (win_integ < 1) return r_peaks;
    
    // 有效数据起始位置 (滤波+积分导致的延迟)
    const size_t start_index = 5 + win_integ - 1;

    // 2. 带通滤波 (通过移动平均近似)
    std::vector<float> filtered(n, 0.0f);
    // 低通滤波 (5点移动平均)
    for (size_t i = 4; i < n; i++) {
        filtered[i] = (ecg_signal[i-4] + ecg_signal[i-3] + 
                       ecg_signal[i-2] + ecg_signal[i-1] + 
                       ecg_signal[i]) / 5.0f;
    }
    
    // 3. 微分 (增强QRS斜率)
    std::vector<float> diff(n, 0.0f);
    for (size_t i = 5; i < n; i++) {
        diff[i] = filtered[i] - filtered[i-1];
    }
    
    // 4. 平方 (放大高频分量)
    std::vector<float> sqrd(n, 0.0f);
    for (size_t i = 0; i < n; i++) {
        sqrd[i] = diff[i] * diff[i];
    }
    
    // 5. 移动平均积分 (突出QRS复合波)
    std::vector<float> integrated(n, 0.0f);
    for (size_t i = start_index; i < n; i++) {
        float sum = 0.0f;
        for (int j = 0; j < win_integ; j++) {
            sum += sqrd[i - j];
        }
        integrated[i] = sum / win_integ;
    }
    
    // 6. 自适应阈值检测
    float threshold = 0.0f;
    float peak_value = 0.0f;
    const size_t min_interval = static_cast<size_t>(0.2f * sample_rate); // 200ms最小间隔
    
    // 初始阈值设置 (使用前1秒数据，适应较短数据)
    const size_t init_win = std::min(static_cast<size_t>(1 * sample_rate), n - start_index);
    if (init_win > 10) {
        auto max_it = std::max_element(integrated.begin() + start_index, 
                                      integrated.begin() + start_index + init_win);
        threshold = 0.2f * (*max_it); // 进一步降低阈值到20%，提高检测敏感性
    } else {
        threshold = 0.2f * (*std::max_element(integrated.begin(), integrated.end())); // 降低阈值到20%
    }
    
    // 噪声和信号峰值跟踪
    float noise_peak = 0.25f * threshold;
    float signal_peak = threshold;
    const float decay_rate = 0.125f; // 阈值衰减率
    
    size_t last_peak = 0;
    bool found_peak = false;
    
    for (size_t i = start_index + 1; i < n - 1; i++) {
        // 检测峰值 (大于前后两点)
        if (integrated[i] > integrated[i-1] && 
            integrated[i] > integrated[i+1] && 
            integrated[i] > threshold) {
            
            // 检查最小间隔
            if (last_peak == 0 || i - last_peak > min_interval) {
                r_peaks.push_back(static_cast<float>(i));
                last_peak = i;
                found_peak = true;
                peak_value = integrated[i];
            }
        }
        
        // 自适应阈值更新
        if (found_peak) {
            // 检测到峰值后更新信号阈值
            signal_peak = decay_rate * peak_value + (1 - decay_rate) * signal_peak;
            found_peak = false;
        } else {
            // 未检测到峰值时更新噪声阈值
            if (integrated[i] > noise_peak) {
                noise_peak = decay_rate * integrated[i] + (1 - decay_rate) * noise_peak;
            }
        }
        
        // 组合阈值 (信号和噪声阈值的加权平均)
        threshold = 0.25f * signal_peak + 0.75f * noise_peak;
    }
    
    return r_peaks;
}

// 脉搏波峰检测 - 改进版本
std::vector<float> MetricsCalculator::detect_pulse_peaks(const std::vector<float>& ppg_signal, float sample_rate) {
    std::vector<float> pulse_peaks;
    if (ppg_signal.empty() || sample_rate <= 0) return pulse_peaks;
    
    const size_t n = ppg_signal.size();
    
    // 1) 轻量平滑（5点移动平均），提升SNR以适应低采样率(50Hz)
    std::vector<float> smooth(n, 0.0f);
    const size_t ma_win = 5; // ≈100ms@50Hz
    float acc = 0.0f;
    for (size_t i = 0; i < n; ++i) {
        acc += ppg_signal[i];
        if (i >= ma_win) acc -= ppg_signal[i - ma_win];
        size_t denom = (i + 1 < ma_win) ? (i + 1) : ma_win;
        smooth[i] = acc / static_cast<float>(denom);
    }
    
    // 2) 参数：窗口与最小间隔
    // 最小脉搏间隔取400ms（≈150bpm上限），避免误检重复峰
    const size_t min_interval = static_cast<size_t>(0.4f * sample_rate);
    // 局部比较窗口：200ms用于极值判断
    const size_t window_size = static_cast<size_t>(0.2f * sample_rate); // 200ms窗口
    // 局部阈值窗口：1.5s，用于计算局部分位数阈值和显著性
    const size_t local_win = static_cast<size_t>(2.0f * sample_rate);
    
    // 3) 使用局部分位阈值与显著性(prominence)判据
    size_t last_peak = 0;
    for (size_t i = window_size; i + window_size < n; ++i) {
        // 局部极大判定
        bool is_peak = true;
        for (size_t j = i - window_size; j <= i + window_size; ++j) {
            if (j != i && smooth[j] >= smooth[i]) { is_peak = false; break; }
        }
        if (!is_peak) continue;
        
        // 局部阈值（基线+分位幅值的一部分）
        size_t l0 = (i > local_win ? i - local_win : 0);
        size_t r0 = std::min(n - 1, i + local_win);
        if (r0 <= l0 + 2) continue;
        std::vector<float> window(smooth.begin() + l0, smooth.begin() + r0 + 1);
        float p5 = compute_percentile(window, 0.05f);
        float p50 = compute_percentile(window, 0.50f);
        float p95 = compute_percentile(window, 0.95f);
        float loc_range = std::max(0.0f, p95 - p5);
        float loc_baseline = p50;
        float loc_threshold = loc_baseline + 0.15f * loc_range; // 低门槛，避免只出1峰
        
        if (smooth[i] <= loc_threshold) continue;
        
        // 显著性：峰值高于局部中位线的幅度需达到一定比例
        float prominence = smooth[i] - loc_baseline;
        if (prominence < 0.1f * loc_range) continue;
        
        // 间隔判定
        if (last_peak != 0 && i - last_peak <= min_interval) continue;
        
        pulse_peaks.push_back(static_cast<float>(i));
        last_peak = i;
    }
    
    return pulse_peaks;
}

// 新增：信号质量评估
float MetricsCalculator::calculate_signal_quality(const std::vector<float>& signal) {
    if (signal.empty()) return 0.0f;
    
    const size_t n = signal.size();
    
    // 1. 计算信噪比 (SNR)
    float signal_power = 0.0f;
    float noise_power = 0.0f;
    
    // 使用简化的功率谱密度计算（避免复杂的FFT）
    // 假设低频部分是信号，高频部分是噪声
    size_t mid_point = n / 2;
    for (size_t i = 0; i < mid_point; i++) {
        signal_power += signal[i] * signal[i];
    }
    for (size_t i = mid_point; i < n; i++) {
        noise_power += signal[i] * signal[i];
    }
    
    float snr = 0.0f;
    if (noise_power > 0.0001f) {
        snr = 10.0f * std::log10(signal_power / noise_power);
    }
    
    // 2. 计算信号连续性
    float continuity_score = 0.0f;
    int discontinuity_count = 0;
    
    for (size_t i = 1; i < n; i++) {
        float diff = std::abs(signal[i] - signal[i-1]);
        if (diff > 10.0f * std::sqrt(noise_power / n)) { // 自适应阈值
            discontinuity_count++;
        }
    }
    
    continuity_score = 100.0f * (1.0f - static_cast<float>(discontinuity_count) / (n - 1));
    
    // 3. 幅度评估
    float max_val = *std::max_element(signal.begin(), signal.end());
    float min_val = *std::min_element(signal.begin(), signal.end());
    float amplitude = max_val - min_val;
    float amplitude_score = clamp(amplitude / 2.0f, 0.0f, 1.0f) * 100.0f;
    
    // 4. 综合质量评分 (0-100)
    float quality_score = 0.0f;
    
    // SNR贡献 (40%)
    if (snr > 20.0f) quality_score += 40.0f;
    else if (snr > 10.0f) quality_score += 30.0f;
    else if (snr > 5.0f) quality_score += 20.0f;
    else if (snr > 0.0f) quality_score += 10.0f;
    
    // 连续性贡献 (30%)
    quality_score += 0.3f * continuity_score;
    
    // 幅度贡献 (30%)
    quality_score += 0.3f * amplitude_score;
    
    return clamp(quality_score, 0.0f, 100.0f);
}

// 综合ECG指标计算
std::map<std::string, float> MetricsCalculator::calculate_all_ecg_metrics(const SensorData& ecg_data, float sample_rate) {
    std::map<std::string, float> metrics;
    
    const auto& signal = get_single_channel(ecg_data);
    if (signal.empty()) return metrics;
    
    // 基础指标
    metrics["heart_rate"] = calculate_heart_rate_ecg(ecg_data, sample_rate);
    metrics["t_wave_amplitude"] = calculate_t_wave_amplitude(signal);
    metrics["qrs_width"] = calculate_qrs_width(signal, sample_rate);
    metrics["st_offset"] = calculate_st_offset(signal, sample_rate);
    metrics["signal_quality"] = calculate_signal_quality(signal);
    
    // 统计指标
    float sum = std::accumulate(signal.begin(), signal.end(), 0.0f);
    float mean = sum / signal.size();
    
    float variance = 0.0f;
    for (float val : signal) {
        variance += (val - mean) * (val - mean);
    }
    variance /= signal.size();
    
    metrics["mean"] = mean;
    metrics["std_dev"] = std::sqrt(std::max(0.0f, variance));
    metrics["min_value"] = *std::min_element(signal.begin(), signal.end());
    metrics["max_value"] = *std::max_element(signal.begin(), signal.end());
    metrics["peak_to_peak"] = metrics["max_value"] - metrics["min_value"];
    
    // HRV指标 (如果能够检测到R峰)
    auto r_peaks = detect_r_peaks(signal, sample_rate);
    if (r_peaks.size() >= 2) {
        std::vector<float> rr_intervals;
        for (size_t i = 1; i < r_peaks.size(); i++) {
            float rr = (r_peaks[i] - r_peaks[i-1]) / sample_rate;
            if (rr > 0.2f && rr < 3.0f) {
                rr_intervals.push_back(rr);
            }
        }
        
        if (rr_intervals.size() >= 2) {
            metrics["sdnn"] = calculate_sdnn(rr_intervals);
            metrics["rmssd"] = calculate_rmssd(rr_intervals);
            metrics["pnn50"] = calculate_pnn50(rr_intervals);
            metrics["triangular_index"] = calculate_triangular_index(rr_intervals);
        }
    }
    
    return metrics;
}

// 综合PPG指标计算
std::map<std::string, float> MetricsCalculator::calculate_all_ppg_metrics(const SensorData& ppg_data, float sample_rate) {
    std::map<std::string, float> metrics;
    
    if (!std::holds_alternative<std::vector<std::vector<float>>>(ppg_data.channel_data) || 
        std::get<std::vector<std::vector<float>>>(ppg_data.channel_data).size() < 1) {
        return metrics;
    }
    
    const auto& channels = std::get<std::vector<std::vector<float>>>(ppg_data.channel_data);
    const auto& signal = channels[0]; // 使用第一通道
    
    if (signal.empty()) return metrics;
    
    // 基础指标
    metrics["heart_rate"] = calculate_heart_rate_ppg(signal, sample_rate);
    metrics["spo2"] = calculate_spo2(ppg_data);
    metrics["perfusion_index"] = calculate_perfusion_index(ppg_data);
    metrics["pulse_width"] = calculate_pulse_width(signal);
    metrics["amplitude_ratio"] = calculate_amplitude_ratio(ppg_data);
    metrics["signal_quality"] = calculate_signal_quality(signal);
    
    // 统计指标
    float sum = std::accumulate(signal.begin(), signal.end(), 0.0f);
    float mean = sum / signal.size();
    
    float variance = 0.0f;
    for (float val : signal) {
        variance += (val - mean) * (val - mean);
    }
    variance /= signal.size();
    
    metrics["mean"] = mean;
    metrics["std_dev"] = std::sqrt(std::max(0.0f, variance));
    metrics["min_value"] = *std::min_element(signal.begin(), signal.end());
    metrics["max_value"] = *std::max_element(signal.begin(), signal.end());
    metrics["peak_to_peak"] = metrics["max_value"] - metrics["min_value"];
    
    // 多通道指标 (如果有多个通道)
    if (channels.size() >= 2) {
        const auto& red_channel = channels[0];
        const auto& ir_channel = channels[1];
        
        if (!red_channel.empty() && !ir_channel.empty()) {
            // 红光和红外光的统计信息
            float red_mean = std::accumulate(red_channel.begin(), red_channel.end(), 0.0f) / red_channel.size();
            float ir_mean = std::accumulate(ir_channel.begin(), ir_channel.end(), 0.0f) / ir_channel.size();
            
            metrics["red_channel_mean"] = red_mean;
            metrics["ir_channel_mean"] = ir_mean;
            metrics["red_ir_ratio"] = (ir_mean > 0.0001f) ? red_mean / ir_mean : 0.0f;
        }
    }
    
    return metrics;
}

// 综合HRV指标计算
std::map<std::string, float> MetricsCalculator::calculate_all_hrv_metrics(const std::vector<float>& rr_intervals) {
    std::map<std::string, float> metrics;
    
    if (rr_intervals.size() < 2) return metrics;
    
    // 过滤异常RR间期
    std::vector<float> filtered_rr;
    for (float rr : rr_intervals) {
        if (rr > 0.2f && rr < 3.0f) { // 200ms-3s范围
            filtered_rr.push_back(rr);
        }
    }
    
    if (filtered_rr.size() < 2) return metrics;
    
    // 基础HRV指标
    metrics["sdnn"] = calculate_sdnn(filtered_rr);
    metrics["rmssd"] = calculate_rmssd(filtered_rr);
    metrics["pnn50"] = calculate_pnn50(filtered_rr);
    metrics["triangular_index"] = calculate_triangular_index(filtered_rr);
    
    // 统计指标
    float mean_rr = std::accumulate(filtered_rr.begin(), filtered_rr.end(), 0.0f) / filtered_rr.size();
    metrics["mean_rr"] = mean_rr;
    metrics["mean_hr"] = 60.0f / mean_rr; // 平均心率
    
    // 几何指标
    float geometric_mean = 1.0f;
    for (float rr : filtered_rr) {
        geometric_mean *= rr;
    }
    geometric_mean = std::pow(geometric_mean, 1.0f / filtered_rr.size());
    metrics["geometric_mean"] = geometric_mean;
    
    // 变异系数 (CV = SDNN / mean_RR * 100%)
    if (mean_rr > 0.0001f) {
        metrics["cv"] = (metrics["sdnn"] / mean_rr) * 100.0f;
    }
    
    // 总功率 (所有RR间期的方差)
    float total_power = 0.0f;
    for (float rr : filtered_rr) {
        total_power += (rr - mean_rr) * (rr - mean_rr);
    }
    total_power /= filtered_rr.size();
    metrics["total_power"] = total_power;
    
    return metrics;
}