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 = 50 // 优化：0.2秒窗口（250Hz采样率），进一步提高实时性
    private var overlapSize = 10 // 优化：20%重叠，减少边界效应
    private var stepSize = windowSize - overlapSize // 步长：40个样本
    
    // 数据缓冲区
    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) {
            val windowData = dataBuffer.take(windowSize).toFloatArray()
            val processedWindow = processWindowWithParameters(windowData, sampleRate, lowpassCutoff, notchFreq, notchQ)
            
            if (processedWindow.isNotEmpty()) {
                processedSamples.addAll(processedWindow)
                Log.d("StreamingSignalProcessor", "处理窗口成功，输出数据长度: ${processedWindow.size}")
            } else {
                Log.w("StreamingSignalProcessor", "窗口处理失败，使用原始数据")
                processedSamples.addAll(windowData.toList())
            }
            
            // 移除已处理的数据
            repeat(stepSize) {
                if (dataBuffer.isNotEmpty()) {
                    dataBuffer.removeAt(0)
                }
            }
        }
        
        Log.d("StreamingSignalProcessor", "数据流处理完成，总共处理了 ${processedSamples.size} 个样本")
        
        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. 低通滤波（去除肌电等高频噪声）- 使用80Hz，减少计算量
            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(", ")}")
                }
            }
            
            // 3. 陷波滤波（去除工频干扰）- 可选
            if (notchFreq > 0) {
                val notchResult = signalProcessor.notchFilter(filtered, sampleRate, notchFreq, notchQ)
                if (notchResult == null) {
                    Log.w("StreamingSignalProcessor", "陷波滤波失败，使用低通滤波结果")
                } else {
                    filtered = notchResult
                    Log.d("StreamingSignalProcessor", "陷波滤波成功（${notchFreq}Hz），结果前3个值: ${filtered.take(3).joinToString(", ")}")
                }
            }
            
            Log.d("StreamingSignalProcessor", "窗口数据处理完成，最终结果长度: ${filtered.size}")
            return filtered.toList()
            
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "处理窗口数据异常: ${e.message}", e)
            return windowData.toList() // 异常时返回原始数据
        }
    }
    
    /**
     * 获取缓冲区状态
     */
    fun getBufferStatus(): Map<String, Int> {
        return mapOf(
            "dataBufferSize" to dataBuffer.size,
            "processedDataSize" to processedData.size,
            "windowSize" to windowSize,
            "overlapSize" to overlapSize,
            "stepSize" to stepSize
        )
    }
    
    /**
     * 计算信号质量
     */
    fun calculateSignalQuality(signal: FloatArray): Float {
        if (signal.isEmpty()) return 0.0f
        
        try {
            // 简单的信号质量评估：基于信号幅度和噪声水平
            val mean = signal.average().toFloat()
            val variance = signal.map { (it - mean) * (it - mean) }.average().toFloat()
            val stdDev = kotlin.math.sqrt(variance)
            
            // 信号质量评分（0-1）
            val quality = kotlin.math.min(1.0f, stdDev / 100.0f)
            return quality
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "计算信号质量失败: ${e.message}")
            return 0.0f
        }
    }
    
    /**
     * 带通滤波
     */
    fun bandpassFilter(signal: FloatArray, sampleRate: Float, lowCutoff: Float, highCutoff: Float): FloatArray? {
        return try {
            signalProcessor.bandpassFilter(signal, sampleRate.toDouble(), lowCutoff.toDouble(), highCutoff.toDouble())
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "带通滤波失败: ${e.message}")
            null
        }
    }
    
    /**
     * 高通滤波
     */
    fun highpassFilter(signal: FloatArray, sampleRate: Float, cutoff: Float): FloatArray? {
        return try {
            signalProcessor.highpassFilter(signal, sampleRate.toDouble(), cutoff.toDouble())
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "高通滤波失败: ${e.message}")
            null
        }
    }
    
    /**
     * 低通滤波
     */
    fun lowpassFilter(signal: FloatArray, sampleRate: Float, cutoff: Float): FloatArray? {
        return try {
            signalProcessor.lowpassFilter(signal, sampleRate.toDouble(), cutoff.toDouble())
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "低通滤波失败: ${e.message}")
            null
        }
    }
    
    /**
     * 陷波滤波
     */
    fun notchFilter(signal: FloatArray, sampleRate: Float, frequency: Float, q: Float): FloatArray? {
        return try {
            signalProcessor.notchFilter(signal, sampleRate.toDouble(), frequency.toDouble(), q.toDouble())
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "陷波滤波失败: ${e.message}")
            null
        }
    }
    
    /**
     * 幅度归一化
     */
    fun normalizeAmplitude(signal: FloatArray): FloatArray? {
        return try {
            val result = signal.copyOf()
            signalProcessor.normalizeAmplitude(result)
            result
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "幅度归一化失败: ${e.message}")
            null
        }
    }
    
    /**
     * 实时处理数据块
     */
    fun processRealtimeChunk(signal: FloatArray, sampleRate: Float): FloatArray? {
        return try {
            signalProcessor.processRealtimeChunk(signal, sampleRate.toDouble())
        } catch (e: Exception) {
            Log.e("StreamingSignalProcessor", "实时处理失败: ${e.message}")
            null
        }
    }
}
