package com.example.cmake_project_test

import android.util.Log
import type.SensorData
import java.util.*

/**
 * 流式信号处理器
 * 支持窗口式实时信号处理
 */
class StreamingSignalProcessor {
    
    private val signalProcessor = SignalProcessorJNI()
    private var processorId: Long = -1L
    private var signalProcessorInitialized = false
    
    // 窗口参数 - 针对ECG信号优化，确保心率计算
    private var windowSize = 500 // 优化：2秒窗口（250Hz采样率），确保心率计算
    private var overlapSize = 100 // 优化：20%重叠，减少边界效应
    private var stepSize = windowSize - overlapSize // 步长：400个样本
    
    // 数据缓冲区
    private val dataBuffer = mutableListOf<Float>()
    private val processedData = mutableListOf<Float>()
    private var lastProcessedIndex = 0
    
    // 滤波器参数
    private var sampleRate = 50.0 // 默认采样率
    private var lowpassCutoff = 40.0 // 低通滤波截止频率
    private var notchFreq = 50.0 // 陷波滤波频率
    private var notchQ = 30.0 // 陷波滤波品质因数
    
    // 设备采样率映射
    private val deviceSampleRates = mapOf(
        // 0x4230: EEG, EOG - 250Hz
        0x4230 to 250.0,
        // 0x4211: ECG1, ECG2, EMG1, EMG2 - 250Hz, BR_TEMPERATURE - 50Hz
        0x4211 to 250.0, // 主要采样率，温度单独处理
        // 0x4402: ECG - 250Hz
        0x4402 to 250.0,
        // 0x4302: RED_DATA, IR_DATA - 50Hz
        0x4302 to 50.0,
        // 0x1102: CH_SOUND - 8000Hz
        0x1102 to 8000.0
    )
    
    /**
     * 初始化信号处理器
     */
    fun initialize(): Boolean {
        try {
            signalProcessorInitialized = signalProcessor.createProcessor()
            if (signalProcessorInitialized) {
                processorId = 1L // 使用固定ID
                Log.d("StreamingSignalProcessor", "流式信号处理器初始化成功")
            } else {
                Log.e("StreamingSignalProcessor", "流式信号处理器初始化失败")
            }
            return signalProcessorInitialized
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "信号处理器初始化异常: ${e.message}")
            return false
        }
    }
    
    /**
     * 处理新的数据流（使用默认参数）
     * @param newData 新的数据样本
     * @return 处理后的数据样本
     */
    fun processStreamingData(newData: List<Float>): List<Float> {
        return processStreamingDataWithParameters(newData, sampleRate, lowpassCutoff, notchFreq, notchQ)
    }
    
    /**
     * 处理新的数据流（使用指定参数）
     * @param newData 新的数据样本
     * @param sampleRate 采样率
     * @param lowpassCutoff 低通滤波截止频率
     * @param notchFreq 陷波滤波频率
     * @param notchQ 陷波滤波品质因数
     * @return 处理后的数据样本
     */
    fun processStreamingDataWithParameters(
        newData: List<Float>, 
        sampleRate: Double, 
        lowpassCutoff: Double, 
        notchFreq: Double, 
        notchQ: Double
    ): List<Float> {
        if (processorId == -1L) {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化")
            return newData
        }
        
        Log.d("StreamingSignalProcessor", "开始处理数据流，输入数据长度: ${newData.size}")
        Log.d("StreamingSignalProcessor", "输入数据前3个值: ${newData.take(3).joinToString(", ")}")
        Log.d("StreamingSignalProcessor", "使用参数 - 采样率: ${sampleRate}Hz, 低通: ${lowpassCutoff}Hz, 陷波: ${notchFreq}Hz")
        
        // 添加新数据到缓冲区
        dataBuffer.addAll(newData)
        Log.d("StreamingSignalProcessor", "缓冲区大小: ${dataBuffer.size}, 窗口大小: $windowSize")
        
        val processedSamples = mutableListOf<Float>()
        
        // 当缓冲区有足够数据时进行窗口处理
        while (dataBuffer.size >= windowSize) {
            // 提取当前窗口数据，过滤掉null值
            val windowDataList = dataBuffer.take(windowSize).filterNotNull()
            if (windowDataList.size < windowSize) {
                Log.w("StreamingSignalProcessor", "窗口数据包含null值，跳过处理")
                // 移除无效数据
                repeat(stepSize) {
                    if (dataBuffer.isNotEmpty()) {
                        dataBuffer.removeAt(0)
                    }
                }
                continue
            }
            
            val windowData = windowDataList.toFloatArray()
            Log.d("StreamingSignalProcessor", "提取窗口数据，长度: ${windowData.size}")
            
            // 应用信号处理
            val processedWindow = processWindowWithParameters(windowData, sampleRate, lowpassCutoff, notchFreq, notchQ)
            Log.d("StreamingSignalProcessor", "窗口处理完成，结果长度: ${processedWindow.size}")
            
            // 只保留非重叠部分的结果
            val nonOverlapSize = stepSize
            val nonOverlapData = processedWindow.take(nonOverlapSize)
            processedSamples.addAll(nonOverlapData)
            Log.d("StreamingSignalProcessor", "添加非重叠数据，长度: ${nonOverlapData.size}")
            
            // 移除已处理的数据（保留重叠部分）
            repeat(stepSize) {
                if (dataBuffer.isNotEmpty()) {
                    dataBuffer.removeAt(0)
                }
            }
        }
        
        Log.d("StreamingSignalProcessor", "数据流处理完成，输出长度: ${processedSamples.size}")
        if (processedSamples.isNotEmpty()) {
            Log.d("StreamingSignalProcessor", "输出数据前3个值: ${processedSamples.take(3).joinToString(", ")}")
        }
        
        return processedSamples
    }
    
    /**
     * 处理单个窗口的数据（使用默认参数）
     */
    private fun processWindow(windowData: FloatArray): List<Float> {
        return processWindowWithParameters(windowData, sampleRate, lowpassCutoff, notchFreq, notchQ)
    }
    
    /**
     * 处理单个窗口的数据（使用指定参数）
     * 专业ECG滤波流程：高通(0.05Hz) → 低通(100Hz) → 陷波(可选)
     */
    private fun processWindowWithParameters(
        windowData: FloatArray, 
        sampleRate: Double, 
        lowpassCutoff: Double, 
        notchFreq: Double, 
        notchQ: Double
    ): List<Float> {
        try {
            Log.d("StreamingSignalProcessor", "开始处理窗口数据，数据长度: ${windowData.size}")
            Log.d("StreamingSignalProcessor", "窗口数据前3个值: ${windowData.take(3).joinToString(", ")}")
            Log.d("StreamingSignalProcessor", "使用参数 - 采样率: ${sampleRate}Hz, 低通: ${lowpassCutoff}Hz, 陷波: ${notchFreq}Hz")
            
            var filtered = windowData
            
            // 1. 高通滤波（去除基线漂移）- 使用0.05Hz，最大限度保留ST段形态
            val highpassCutoff = 0.05 // 诊断模式：0.05Hz，稳定基线
            val highpassResult = signalProcessor.highpassFilter(filtered, sampleRate, highpassCutoff)
            if (highpassResult == null) {
                Log.w("StreamingSignalProcessor", "高通滤波失败，使用原始数据")
            } else {
                filtered = highpassResult
                Log.d("StreamingSignalProcessor", "高通滤波成功（${highpassCutoff}Hz），结果前3个值: ${filtered.take(3).joinToString(", ")}")
            }
            
            // 2. 低通滤波（去除肌电等高频噪声）- 使用100Hz，平衡信号清晰度和噪声抑制
            if (lowpassCutoff > 0) {
                val lowpassResult = signalProcessor.lowpassFilter(filtered, sampleRate, lowpassCutoff)
                if (lowpassResult == null) {
                    Log.w("StreamingSignalProcessor", "低通滤波失败，使用高通滤波结果")
                } else {
                    filtered = lowpassResult
                    Log.d("StreamingSignalProcessor", "低通滤波成功（${lowpassCutoff}Hz），结果前3个值: ${filtered.take(3).joinToString(", ")}")
                }
            } else {
                Log.d("StreamingSignalProcessor", "跳过低通滤波（低通截止频率为0）")
            }
            
            // 3. 陷波滤波（去除工频干扰）- 默认关闭，用户可手动开启
            if (notchFreq > 0) {
                val notchFiltered = signalProcessor.notchFilter(filtered, sampleRate, notchFreq, notchQ)
                if (notchFiltered == null) {
                    Log.w("StreamingSignalProcessor", "陷波滤波失败，使用低通滤波结果")
                    Log.d("StreamingSignalProcessor", "返回低通滤波结果，前3个值: ${filtered.take(3).joinToString(", ")}")
                    return filtered.toList()
                } else {
                    Log.d("StreamingSignalProcessor", "陷波滤波成功（${notchFreq}Hz, Q=${notchQ}），结果前3个值: ${notchFiltered.take(3).joinToString(", ")}")
                    return notchFiltered.toList()
                }
            } else {
                Log.d("StreamingSignalProcessor", "跳过陷波滤波（默认关闭），返回低通滤波结果")
                return filtered.toList()
            }
            
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "窗口处理异常: ${e.message}")
            return windowData.toList()
        }
    }
    
    /**
     * 根据数据类型获取合适的采样率
     */
    private fun getSampleRateForDataType(dataType: type.SensorData.DataType): Double {
        return when (dataType) {
            type.SensorData.DataType.EEG -> 250.0
            type.SensorData.DataType.ECG_2LEAD, type.SensorData.DataType.ECG_12LEAD, type.SensorData.DataType.PW_ECG_SL -> 250.0
            type.SensorData.DataType.PPG -> 50.0
            type.SensorData.DataType.STETHOSCOPE -> 8000.0
            type.SensorData.DataType.SNORE -> 8000.0
            type.SensorData.DataType.RESPIRATION -> 50.0
            else -> 50.0 // 默认采样率
        }
    }
    
    /**
     * 根据数据类型获取合适的滤波器参数
     * 返回格式: Triple<低通截止频率, 陷波频率, 陷波品质因数>
     */
    private fun getFilterParametersForDataType(dataType: type.SensorData.DataType): Triple<Double, Double, Double> {
        return when (dataType) {
            type.SensorData.DataType.EEG -> {
                // EEG: 低通40Hz, 陷波50Hz
                Triple(40.0, 50.0, 30.0)
            }
            type.SensorData.DataType.ECG_2LEAD, type.SensorData.DataType.ECG_12LEAD, type.SensorData.DataType.PW_ECG_SL -> {
                // ECG: 专业ECG滤波参数
                // 低通100Hz (平衡信号清晰度和噪声抑制)
                // 陷波50Hz (中国工频)
                // 品质因数10 (避免过度滤波)
                Triple(100.0, 50.0, 10.0)
            }
            type.SensorData.DataType.PPG -> {
                // PPG: 低通10Hz, 陷波50Hz
                Triple(10.0, 50.0, 30.0)
            }
            type.SensorData.DataType.MIT_BIH -> {
                // MIT-BIH: 低通40Hz, 陷波50Hz
                Triple(40.0, 50.0, 30.0)
            }
            type.SensorData.DataType.STETHOSCOPE -> {
                // 听诊器: 低通4000Hz, 陷波50Hz
                Triple(4000.0, 50.0, 30.0)
            }
            type.SensorData.DataType.SNORE -> {
                // 鼾声: 低通4000Hz, 陷波50Hz
                Triple(4000.0, 50.0, 30.0)
            }
            type.SensorData.DataType.RESPIRATION -> {
                // 呼吸: 低通1Hz, 不陷波
                Triple(1.0, 0.0, 0.0)
            }
            else -> {
                // 默认参数
                Triple(40.0, 50.0, 30.0)
            }
        }
    }
    
    /**
     * 处理传感器数据包
     */
    fun processSensorData(sensorData: SensorData): SensorData {
        val channelData = sensorData.getChannelData()
        if (channelData == null || channelData.isEmpty()) {
            return sensorData
        }
        
        try {
            // 根据数据类型设置采样率和滤波器参数
            val dataType = sensorData.getDataType()
            val sampleRate = getSampleRateForDataType(dataType)
            val (lowpassCutoff, notchFreq, notchQ) = getFilterParametersForDataType(dataType)
            
            Log.d("StreamingSignalProcessor", "处理数据类型: $dataType, 采样率: ${sampleRate}Hz, 低通: ${lowpassCutoff}Hz, 陷波: ${notchFreq}Hz")
            
            // 处理每个通道
            val processedChannels = channelData.map { channel ->
                val channelData = channel.toFloatArray()
                val processedData = processStreamingDataWithParameters(channelData.toList(), sampleRate, lowpassCutoff, notchFreq, notchQ)
                processedData.toFloatArray()
            }
            
            // 创建处理后的传感器数据
            val processedSensorData = SensorData()
            processedSensorData.setDataType(sensorData.getDataType())
            processedSensorData.setTimestamp(sensorData.getTimestamp())
            processedSensorData.setPacketSn(sensorData.getPacketSn())
            processedSensorData.setChannelData(processedChannels.map { it.toList() })
            
            return processedSensorData
            
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "处理传感器数据异常: ${e.message}")
            return sensorData
        }
    }
    
    /**
     * 批量处理传感器数据包
     */
    fun processSensorDataList(sensorDataList: List<SensorData>): List<SensorData> {
        return sensorDataList.map { processSensorData(it) }
    }
    
    /**
     * 获取缓冲区状态
     */
    fun getBufferStatus(): Map<String, Int> {
        return mapOf(
            "buffer_size" to dataBuffer.size,
            "window_size" to windowSize,
            "overlap_size" to overlapSize,
            "step_size" to stepSize
        )
    }
    
    /**
     * 清空缓冲区
     */
    fun clearBuffer() {
        dataBuffer.clear()
        processedData.clear()
        lastProcessedIndex = 0
        Log.d("StreamingSignalProcessor", "缓冲区已清空")
    }
    
    /**
     * 设置窗口参数
     */
    fun setWindowParameters(windowSize: Int, overlapSize: Int) {
        this.windowSize = windowSize
        this.overlapSize = overlapSize
        this.stepSize = windowSize - overlapSize
        Log.d("StreamingSignalProcessor", "窗口参数已更新: 窗口大小=$windowSize, 重叠大小=$overlapSize")
    }
    
    /**
     * 设置滤波器参数
     */
    fun setFilterParameters(lowpassCutoff: Double, notchFreq: Double, notchQ: Double) {
        this.lowpassCutoff = lowpassCutoff
        this.notchFreq = notchFreq
        this.notchQ = notchQ
        Log.d("StreamingSignalProcessor", "滤波器参数已更新")
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            if (processorId != -1L) {
                signalProcessor.destroyProcessor()
                processorId = -1L
            }
            clearBuffer()
            Log.d("StreamingSignalProcessor", "流式信号处理器资源已清理")
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "清理资源时发生错误: ${e.message}")
        }
    }
    
    // 委托给SignalProcessorJNI的方法
    fun normalizeAmplitude(signal: FloatArray): FloatArray? {
        if (signalProcessorInitialized) {
            signalProcessor.normalizeAmplitude(signal)
            return signal // normalizeAmplitude修改原数组，返回原数组
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            return signal
        }
    }
    
    fun bandpassFilter(signal: FloatArray, sampleRate: Float, lowFreq: Float, highFreq: Float): FloatArray? {
        return if (signalProcessorInitialized) {
            signalProcessor.bandpassFilter(signal, sampleRate.toDouble(), lowFreq.toDouble(), highFreq.toDouble())
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            signal
        }
    }
    
    fun highpassFilter(signal: FloatArray, sampleRate: Float, cutoffFreq: Float): FloatArray? {
        return if (signalProcessorInitialized) {
            signalProcessor.highpassFilter(signal, sampleRate.toDouble(), cutoffFreq.toDouble())
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            signal
        }
    }
    
    fun lowpassFilter(signal: FloatArray, sampleRate: Float, cutoffFreq: Float): FloatArray? {
        return if (signalProcessorInitialized) {
            signalProcessor.lowpassFilter(signal, sampleRate.toDouble(), cutoffFreq.toDouble())
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            signal
        }
    }
    
    fun notchFilter(signal: FloatArray, sampleRate: Float, notchFreq: Float): FloatArray? {
        return if (signalProcessorInitialized) {
            signalProcessor.notchFilter(signal, sampleRate.toDouble(), notchFreq.toDouble())
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            signal
        }
    }
    
    fun processRealtimeChunk(signal: FloatArray, sampleRate: Float): FloatArray? {
        return if (signalProcessorInitialized) {
            signalProcessor.processRealtimeChunk(signal, sampleRate.toDouble())
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回原始信号")
            signal
        }
    }
    
    fun calculateSignalQuality(signal: FloatArray): Float {
        return if (signalProcessorInitialized) {
            signalProcessor.calculateSignalQuality(signal)
        } else {
            Log.w("StreamingSignalProcessor", "信号处理器未初始化，返回默认质量值")
            0.0f
        }
    }
}
