package com.example.cmake_project_test

import android.util.Log
import type.SensorData
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * 数据管理类
 * 负责数据解析、缓冲管理和原生方法调用
 */
class DataManager(private val nativeCallback: NativeMethodCallback) {
    
    // 添加实时数据回调接口
    interface RealTimeDataCallback {
        fun onProcessedDataAvailable(channelIndex: Int, processedData: List<Float>)
        fun onStreamingProgress(progress: Int, totalSamples: Int, processedSamples: Int)
        fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) // 新增：原始数据回调
    }
    
    private var realTimeCallback: RealTimeDataCallback? = null
    private val additionalCallbacks = mutableListOf<RealTimeDataCallback>()
    
    fun setRealTimeCallback(callback: RealTimeDataCallback) {
        this.realTimeCallback = callback
    }
    
    fun addRealTimeCallback(callback: RealTimeDataCallback) {
        if (!additionalCallbacks.contains(callback)) {
            additionalCallbacks.add(callback)
        }
    }
    
    fun removeRealTimeCallback(callback: RealTimeDataCallback) {
        try {
            additionalCallbacks.remove(callback)
            Log.d("DataManager", "已移除实时数据回调，剩余回调数: ${additionalCallbacks.size}")
        } catch (e: Exception) {
            Log.e("DataManager", "移除实时数据回调失败: ${e.message}", e)
        }
    }
    
    private var parserHandle: Long = 0L
    private val rawStream = ByteArrayOutputStream(4096)
    private val packetBuffer = mutableListOf<SensorData>()
    private val mappedPacketBuffer = mutableListOf<SensorData>() // 新增：映射后的数据包缓冲区
    private var totalPacketsParsed = 0L
    
    // 信号处理相关
    private var streamingSignalProcessor: StreamingSignalProcessor? = null
    private var streamingSignalProcessorInitialized = false
    private val processedPackets = mutableListOf<SensorData>()
    private var filterSettings = FilterSettings()
    
    // 通道映射相关
    private var dataMapper: DataMapper? = null
    private var dataMapperInitialized = false
    
    // 指标计算相关
    private var indicatorCalculator: IndicatorCalculator? = null
    private var indicatorCalculatorInitialized = false
    private val calculatedMetrics = mutableListOf<Map<String, Float>>()
    private var latestMetrics: Map<String, Float> = emptyMap()
    
    // 流式数据处理相关
    private val channelBuffers = mutableMapOf<Int, MutableList<Float>>() // 通道号 -> 数据缓冲区
    private val processedChannelBuffers = mutableMapOf<Int, MutableList<Float>>() // 处理后的通道数据
    private val processingWindowSize = 100 // 优化：0.4秒窗口（250Hz采样率），进一步提高实时性
    private val minSamplesForMetrics = 25 // 优化：25个样本（0.1秒@250Hz），快速响应
    private var currentDataType: type.SensorData.DataType? = null // 当前数据类型
    private var lastProcessTime = 0L // 上次处理时间
    private val processingInterval = 25L // 优化：25ms处理间隔，进一步提高实时性
    private var totalProcessedSamples = 0L // 总处理样本数
    
    // 陷波滤波器状态
    var notchFilterEnabled = false
    
    /**
     * 确保解析器已创建
     */
    fun ensureParser() {
        if (parserHandle == 0L) {
            try {
                parserHandle = nativeCallback.createStreamParser()
                Log.d("DataManager", "JNI解析器创建成功，句柄: $parserHandle")
            } catch (e: Exception) {
                Log.e("DataManager", "JNI解析器创建失败: ${e.message}", e)
                throw RuntimeException("无法创建JNI解析器", e)
            }
        }
    }
    
    /**
     * 处理蓝牙通知数据块
     */
    fun onBleNotify(chunk: ByteArray) {
        if (chunk.isEmpty()) {
            Log.w("DataManager", "接收到空的蓝牙数据块")
            return
        }
        
        Log.d("DataManager", "接收到蓝牙数据: ${chunk.size} 字节")
        Log.d("DataManager", "数据前10字节: ${chunk.take(10).joinToString(", ") { "0x%02X".format(it) }}")
        
        ensureParser()
        rawStream.write(chunk)

        try {
            nativeCallback.streamParserAppend(parserHandle, chunk)
        } catch (e: Exception) {
            Log.e("DataManager", "JNI数据追加失败: ${e.message}", e)
            return // 不继续处理，避免进一步错误
        }

        // 拉取解析出的数据包
        val packets = try {
            nativeCallback.streamParserDrainPackets(parserHandle)
        } catch (e: Exception) {
            Log.e("DataManager", "JNI数据拉取失败: ${e.message}", e)
            null
        }

        Log.d("DataManager", "解析结果: ${if (packets != null) packets.size else 0} 个数据包")
        
        if (!packets.isNullOrEmpty()) {
            totalPacketsParsed += packets.size
            packetBuffer.addAll(packets)
            
            Log.d("DataManager", "解析出 ${packets.size} 个数据包")
            
            // 立即发送原始数据到图表显示（优先显示原始数据）
            sendRawDataToCharts(packets)
            
            // 注释掉后台处理，只显示原始数据
            // processStreamingData(packets)
        } else {
            Log.w("DataManager", "没有解析出有效数据包，尝试生成测试数据")
            
            // 如果原生解析器没有解析出数据包，生成一些测试数据来验证图表显示
            generateTestDataForChart()
        }
    }
    
    /**
     * 生成测试数据用于验证图表显示
     */
    private fun generateTestDataForChart() {
        try {
            Log.d("DataManager", "生成测试数据用于验证图表显示")
            
            // 生成模拟的单导联ECG数据
            val testData = mutableListOf<Float>()
            val sampleCount = 100 // 生成100个样本点
            
            for (i in 0 until sampleCount) {
                val t = i.toFloat() / 10f // 时间参数
                val value = (Math.sin(t * 2 * Math.PI) * 100 + 
                           Math.sin(t * 4 * Math.PI) * 50 + 
                           Math.sin(t * 8 * Math.PI) * 25).toFloat()
                testData.add(value)
            }
            
            Log.d("DataManager", "生成测试数据: ${testData.size} 个样本点")
            Log.d("DataManager", "测试数据前5个值: ${testData.take(5).joinToString(", ")}")
            
            // 发送测试数据到图表
            if (realTimeCallback != null) {
                realTimeCallback!!.onRawDataAvailable(0, testData)
                Log.d("DataManager", "已发送测试数据到图表")
            } else {
                Log.e("DataManager", "realTimeCallback 为空，无法发送测试数据")
            }
            
        } catch (e: Exception) {
            Log.e("DataManager", "生成测试数据失败: ${e.message}", e)
        }
    }
    
    /**
     * 确保数据映射器已初始化
     */
    fun ensureDataMapper() {
        if (!dataMapperInitialized) {
            try {
                Log.d("DataManager", "开始创建数据映射器实例...")
                dataMapper = DataMapper()
                Log.d("DataManager", "数据映射器实例创建成功")
                
                Log.d("DataManager", "开始初始化数据映射器...")
                dataMapperInitialized = dataMapper?.initialize() ?: false
            if (dataMapperInitialized) {
                Log.d("DataManager", "数据映射器初始化成功")
            } else {
                Log.e("DataManager", "数据映射器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "数据映射器初始化异常: ${e.message}", e)
                dataMapperInitialized = false
            }
        }
    }
    
    /**
     * 确保指标计算器已初始化
     */
    fun ensureIndicatorCalculator() {
        if (!indicatorCalculatorInitialized) {
            try {
                Log.d("DataManager", "开始创建指标计算器实例...")
                indicatorCalculator = IndicatorCalculator()
                Log.d("DataManager", "指标计算器实例创建成功")
                
                Log.d("DataManager", "开始初始化指标计算器...")
                indicatorCalculatorInitialized = indicatorCalculator?.initialize() ?: false
            if (indicatorCalculatorInitialized) {
                Log.d("DataManager", "指标计算器初始化成功")
            } else {
                Log.e("DataManager", "指标计算器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "指标计算器初始化异常: ${e.message}", e)
                indicatorCalculatorInitialized = false
            }
        }
    }
    
    /**
     * 确保流式信号处理器已初始化
     */
    fun ensureStreamingSignalProcessor() {
        if (!streamingSignalProcessorInitialized) {
            try {
                Log.d("DataManager", "开始创建流式信号处理器实例...")
                streamingSignalProcessor = StreamingSignalProcessor()
                Log.d("DataManager", "流式信号处理器实例创建成功")
                
                Log.d("DataManager", "开始初始化流式信号处理器...")
                streamingSignalProcessorInitialized = streamingSignalProcessor?.initialize() ?: false
            if (streamingSignalProcessorInitialized) {
                Log.d("DataManager", "流式信号处理器初始化成功")
            } else {
                Log.e("DataManager", "流式信号处理器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "流式信号处理器初始化异常: ${e.message}", e)
                streamingSignalProcessorInitialized = false
            }
        }
    }
    
    /**
     * 立即发送映射后的数据到图表显示
     */
    private fun sendRawDataToCharts(packets: List<SensorData>) {
        if (packets.isEmpty()) {
            return
        }
        
        // 确保数据映射器已初始化
        ensureDataMapper()
        if (!dataMapperInitialized || dataMapper == null) {
            Log.w("DataManager", "数据映射器未初始化，使用原始数据")
            sendRawDataToChartsDirect(packets)
            return
        }
        
        try {
            Log.d("DataManager", "开始数据映射处理，输入数据包数: ${packets.size}")
            
            // 清空之前的映射数据
            mappedPacketBuffer.clear()
            
            // 对每个数据包进行映射
            val mappedPackets = mutableListOf<SensorData>()
            for (packet in packets) {
                val mappedPacket = dataMapper?.mapSensorData(packet)
                if (mappedPacket != null) {
                    mappedPackets.add(mappedPacket)
                    mappedPacketBuffer.add(mappedPacket) // 保存到映射缓冲区
                    Log.d("DataManager", "数据包映射成功，原始通道数: ${packet.getChannelData()?.size ?: 0}, 映射后通道数: ${mappedPacket.getChannelData()?.size ?: 0}")
                } else {
                    Log.w("DataManager", "数据包映射失败，使用原始数据")
                    mappedPackets.add(packet)
                    mappedPacketBuffer.add(packet)
                }
            }
            
            // 发送映射后的数据到图表
            sendMappedDataToCharts(mappedPackets)
            
        } catch (e: Exception) {
            Log.e("DataManager", "数据映射处理失败: ${e.message}", e)
            // 映射失败时使用原始数据
            sendRawDataToChartsDirect(packets)
        }
    }
    
    /**
     * 发送映射后的数据到图表
     */
    private fun sendMappedDataToCharts(mappedPackets: List<SensorData>) {
        if (mappedPackets.isEmpty()) {
            return
        }
        
        var totalDataPoints = 0
        
        // 处理映射后的数据包
        for (packet in mappedPackets) {
            val channelData = packet.getChannelData()
            if (channelData != null && channelData.isNotEmpty()) {
                // 发送所有映射后的通道数据
                for (i in channelData.indices) {
                    val channel = channelData[i]
                    if (channel.isNotEmpty()) {
                        // 发送给主回调
                        realTimeCallback?.onRawDataAvailable(i, channel)
                        // 发送给所有附加回调
                        additionalCallbacks.forEach { callback ->
                            callback.onRawDataAvailable(i, channel)
                        }
                        totalDataPoints += channel.size
                    }
                }
            }
        }
        
        if (totalDataPoints > 0) {
            Log.d("DataManager", "发送映射后数据到图表: ${totalDataPoints} 个数据点")
        }
    }
    
    /**
     * 直接发送原始数据到图表（备用方法）
     */
    private fun sendRawDataToChartsDirect(packets: List<SensorData>) {
        if (packets.isEmpty()) {
            return
        }
        
        var totalDataPoints = 0
        
        // 处理原始数据包
        for (packet in packets) {
            val channelData = packet.getChannelData()
            if (channelData != null && channelData.isNotEmpty()) {
                // 对于单导联数据，我们主要关注第一个通道（通常是导联I或II）
                val primaryChannel = channelData[0]
                if (primaryChannel.isNotEmpty()) {
                    // 立即发送单导联数据到图表
                    realTimeCallback?.onRawDataAvailable(0, primaryChannel) // 使用通道0表示主导联
                    // 发送给所有附加回调
                    additionalCallbacks.forEach { callback ->
                        callback.onRawDataAvailable(0, primaryChannel)
                    }
                    totalDataPoints += primaryChannel.size
                    
                    // 如果有其他通道（如参考通道），也发送
                    if (channelData.size > 1) {
                        for (i in 1 until channelData.size) {
                            val additionalChannel = channelData[i]
                            if (additionalChannel.isNotEmpty()) {
                                realTimeCallback?.onRawDataAvailable(i, additionalChannel)
                                additionalCallbacks.forEach { callback ->
                                    callback.onRawDataAvailable(i, additionalChannel)
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // 只在需要时记录日志
        if (totalDataPoints > 0) {
            Log.d("DataManager", "发送原始数据到图表: ${totalDataPoints} 个数据点")
        }
    }
    
    /**
     * 流式数据处理 - 专门处理单导联蓝牙数据
     */
    private fun processStreamingData(packets: List<SensorData>) {
        if (packets.isEmpty()) return
        
        Log.d("DataManager", "开始单导联流式数据处理，处理 ${packets.size} 个数据包")
        
        // 对于单导联数据，我们直接使用原始数据包，不进行复杂的通道映射
        val mappedPackets = packets
            
        // 2. 按通道合并数据 - 单导联处理
        for (packet in mappedPackets) {
            val dataType = packet.getDataType()
            if (currentDataType == null) {
                currentDataType = dataType
                Log.d("DataManager", "设置单导联数据类型: $dataType")
            }
            
            val channelData = packet.getChannelData()
            if (channelData != null && channelData.isNotEmpty()) {
                // 对于单导联数据，主要处理第一个通道
                val primaryChannel = channelData[0]
                if (!channelBuffers.containsKey(0)) {
                    channelBuffers[0] = mutableListOf()
                    processedChannelBuffers[0] = mutableListOf()
                }
                channelBuffers[0]!!.addAll(primaryChannel)
                
                // 如果有其他通道，也处理
                for (i in 1 until channelData.size) {
                    val additionalChannel = channelData[i]
                    if (!channelBuffers.containsKey(i)) {
                        channelBuffers[i] = mutableListOf()
                        processedChannelBuffers[i] = mutableListOf()
                    }
                    channelBuffers[i]!!.addAll(additionalChannel)
                }
            }
        }
        
        // 检查是否达到处理条件 - 单导联优化
        val totalSamples = channelBuffers.values.firstOrNull()?.size ?: 0
        if (totalSamples > 0) {
            Log.d("DataManager", "单导联当前总样本数: $totalSamples, 需要样本数: $minSamplesForMetrics")
        }
        
        // 3. 检查处理条件：数据量足够且时间间隔合适
        val currentTime = System.currentTimeMillis()
        val shouldProcess = totalSamples >= minSamplesForMetrics && 
                           (currentTime - lastProcessTime) >= processingInterval
        
        if (shouldProcess) {
            Log.d("DataManager", "满足单导联处理条件，开始流式信号处理和指标计算")
            processStreamingWindow()
            lastProcessTime = currentTime
        } else {
            Log.d("DataManager", "不满足单导联处理条件 - 数据量: ${totalSamples}/${minSamplesForMetrics}, 时间间隔: ${currentTime - lastProcessTime}ms/${processingInterval}ms")
        }
        
        // 累积单导联数据包列表（用于UI显示）
        this.processedPackets.addAll(mappedPackets)
        
        // 添加单导联调试信息
        Log.d("DataManager", "单导联数据处理完成 - 输入: ${packets.size}个数据包, 处理: ${mappedPackets.size}个数据包")
        Log.d("DataManager", "累积单导联数据包总数: ${this.processedPackets.size}")
    }
    
    /**
     * 处理流式数据窗口
     */
    private fun processStreamingWindow() {
        ensureStreamingSignalProcessor()
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) {
            Log.w("DataManager", "流式处理器未初始化，跳过处理")
            return
        }
        
        try {
            Log.d("DataManager", "开始处理流式数据窗口")
            
            // 获取采样率
            val sampleRate = when (currentDataType) {
                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 -> 250.0
            }
            
            Log.d("DataManager", "使用采样率: ${sampleRate}Hz，数据类型: $currentDataType")
            
            // 处理所有通道的数据
            val processedChannels = mutableListOf<List<Float>>()
            var localProcessedSamples = 0L
            
            for ((channelIndex, channelData) in channelBuffers) {
                if (channelData.size >= minSamplesForMetrics) {
                    Log.d("DataManager", "处理通道 $channelIndex，数据长度: ${channelData.size}")
                    
                    // 应用专业ECG信号处理：高通(0.05Hz) → 低通(100Hz) → 陷波(可选)
                    val notchFreq = if (notchFilterEnabled) 50.0 else 0.0 // 根据用户设置决定是否启用陷波滤波
                    val processedData = streamingSignalProcessor!!.processStreamingDataWithParameters(
                        channelData,
                        250.0, // ECG采样率：250Hz
                        100.0, // 低通滤波截止频率：100Hz（平衡信号清晰度和噪声抑制）
                        notchFreq, // 陷波滤波频率：50Hz或0Hz（根据用户设置）
                        10.0   // 陷波滤波品质因数：10（避免过度滤波）
                    )
                    
                    if (processedData.isNotEmpty()) {
                        processedChannels.add(processedData)
                        processedChannelBuffers[channelIndex]?.addAll(processedData)
                        localProcessedSamples += processedData.size
                        Log.d("DataManager", "通道 $channelIndex 处理完成，处理后数据长度: ${processedData.size}")
                    } else {
                        Log.w("DataManager", "通道 $channelIndex 处理失败，返回空数据")
                        processedChannels.add(channelData) // 使用原始数据
                    }
                } else {
                    Log.w("DataManager", "通道 $channelIndex 数据不足，跳过处理")
                    processedChannels.add(channelData) // 使用原始数据
                }
            }
            
            Log.d("DataManager", "所有通道处理完成，总共处理了 $localProcessedSamples 个样本")
            
            // 立即发送处理后的数据到图表
            if (processedChannels.isNotEmpty() && processedChannels[0].isNotEmpty()) {
                val processedData = processedChannels[0]
                Log.d("DataManager", "发送处理后的数据到图表，长度: ${processedData.size}")
                Log.d("DataManager", "处理后数据前3个值: ${processedData.take(3).joinToString(", ")}")
                
                realTimeCallback?.onRawDataAvailable(0, processedData)
                // 发送给所有附加回调
                additionalCallbacks.forEach { callback ->
                    callback.onRawDataAvailable(0, processedData)
                }
                Log.d("DataManager", "已发送处理后数据到图表")
            }
            
            // 计算指标（使用第一个处理后的通道）
            Log.d("DataManager", "准备计算指标，处理后通道数量: ${processedChannels.size}")
            if (processedChannels.isNotEmpty()) {
                Log.d("DataManager", "第一个通道数据长度: ${processedChannels[0].size}, 最小要求: $minSamplesForMetrics")
                
                if (processedChannels[0].size >= minSamplesForMetrics) {
                    ensureIndicatorCalculator()
                if (indicatorCalculatorInitialized && indicatorCalculator != null) {
                    try {
                        // 创建临时的SensorData用于指标计算
                        val tempSensorData = SensorData()
                        tempSensorData.setDataType(currentDataType!!)
                        tempSensorData.setTimestamp(System.currentTimeMillis())
                        tempSensorData.setPacketSn(0)
                        tempSensorData.setChannelData(processedChannels)
                        
                        val metrics = indicatorCalculator!!.processCompletePipeline(tempSensorData, sampleRate.toFloat())
                        if (metrics != null && metrics.isNotEmpty()) {
                            Log.d("DataManager", "指标计算成功，获得 ${metrics.size} 个指标")
                            
                            // 特别关注心率指标
                            val heartRate = metrics["heart_rate"]
                            if (heartRate != null) {
                                Log.d("DataManager", "心率计算结果: $heartRate bpm")
                            } else {
                                Log.w("DataManager", "心率计算结果为空")
                            }
                            
                            latestMetrics = metrics
                            calculatedMetrics.clear()
                            calculatedMetrics.add(metrics)
                            
                            // 记录处理统计
                            this.totalProcessedSamples += localProcessedSamples
                        } else {
                            Log.w("DataManager", "指标计算返回空结果")
                        }
                    } catch (e: Exception) {
                        Log.e("DataManager", "指标计算失败: ${e.message}")
                    }
                }
            }
            } else {
                Log.w("DataManager", "第一个通道数据长度不足，跳过指标计算")
            }
            
            // 清理缓冲区（保留最后一部分数据用于连续性）
            val keepSamples = minSamplesForMetrics / 2
            channelBuffers.forEach { (channel, buffer) ->
                if (buffer.size > keepSamples) {
                    val toRemove = buffer.size - keepSamples
                    repeat(toRemove) {
                        if (buffer.isNotEmpty()) {
                            buffer.removeAt(0)
                        }
                    }
                }
            }
            
            // 清理处理后的缓冲区
            processedChannelBuffers.forEach { (channel, buffer) ->
                if (buffer.size > keepSamples) {
                    val toRemove = buffer.size - keepSamples
                    repeat(toRemove) {
                        if (buffer.isNotEmpty()) {
                            buffer.removeAt(0)
                        }
                    }
                }
            }
            
            Log.d("DataManager", "流式数据处理完成，保留 ${keepSamples} 个样本用于连续性")
            
            // 实时回调处理后的数据
            realTimeCallback?.let { callback ->
                processedChannels.forEachIndexed { channelIndex, processedData ->
                    if (processedData.isNotEmpty()) {
                        callback.onProcessedDataAvailable(channelIndex, processedData)
                    }
                }
                
                // 回调处理状态（不显示进度条，只记录状态）
                val totalSamples = channelBuffers.values.firstOrNull()?.size ?: 0
                callback.onStreamingProgress(
                    progress = 0, // 实时处理没有进度概念
                    totalSamples = totalSamples,
                    processedSamples = localProcessedSamples.toInt()
                )
            }
            
        } catch (e: Exception) {
            Log.e("DataManager", "流式数据处理异常: ${e.message}", e)
        }
    }
    
    /**
     * 处理文件数据
     */
    fun processFileData(fileData: ByteArray, progressCallback: ((Int) -> Unit)? = null) {
        Log.d("DataManager", "开始处理文件数据，数据大小: ${fileData.size} 字节")
        
        try {
            val chunkSize = 1024
            var processedBytes = 0
            
            for (i in fileData.indices step chunkSize) {
                val endIndex = minOf(i + chunkSize, fileData.size)
                val chunk = fileData.copyOfRange(i, endIndex)
                
                onBleNotify(chunk)
                processedBytes += chunk.size
                
                // 性能优化：减少进度更新频率
                if (processedBytes % (chunkSize * 10) == 0) {
                    val progress = (processedBytes * 100 / fileData.size).coerceAtMost(100)
                    progressCallback?.invoke(progress)
                }
            }
            
            Log.d("DataManager", "文件数据处理完成，总共处理了 $processedBytes 字节")
            
        } catch (e: Exception) {
            Log.e("DataManager", "处理文件数据时发生错误: ${e.message}", e)
        }
    }
    
    // Getter方法
    fun getPacketBufferSize(): Int = packetBuffer.size
    fun getProcessedPacketsSize(): Int = processedPackets.size
    fun getCalculatedMetricsSize(): Int = calculatedMetrics.size
    fun getRawStreamSize(): Int = rawStream.size()
    fun getTotalPacketsParsed(): Long = totalPacketsParsed
    fun getPacketBuffer(): List<SensorData> = packetBuffer
    fun getProcessedPackets(): List<SensorData> = processedPackets
    fun getCalculatedMetrics(): List<Map<String, Float>> = calculatedMetrics
    fun getLatestMetrics(): Map<String, Float> = latestMetrics
    fun getChannelBuffersStatus(): Map<Int, Int> = channelBuffers.mapValues { it.value.size }
    
    // 流式处理相关getter方法
    fun getProcessedChannelBuffersStatus(): Map<Int, Int> = processedChannelBuffers.mapValues { it.value.size }
    fun getProcessedChannelData(channelIndex: Int): List<Float> = processedChannelBuffers[channelIndex] ?: emptyList()
    fun getTotalProcessedSamples(): Long = totalProcessedSamples
    fun getCurrentDataType(): type.SensorData.DataType? = currentDataType
    fun getProcessingStatus(): Map<String, Any> {
        return mapOf(
            "totalSamples" to (channelBuffers.values.firstOrNull()?.size ?: 0),
            "minSamplesRequired" to minSamplesForMetrics,
            "timeSinceLastProcess" to (System.currentTimeMillis() - lastProcessTime),
            "processingInterval" to processingInterval,
            "currentDataType" to (currentDataType?.name ?: "Unknown"),
            "totalProcessedSamples" to totalProcessedSamples
        )
    }
    
    /**
     * 获取流式信号处理器状态
     */
    fun getStreamingSignalProcessorStatus(): Map<String, Int> {
        return if (streamingSignalProcessorInitialized && streamingSignalProcessor != null) {
            streamingSignalProcessor!!.getBufferStatus()
        } else {
            emptyMap()
        }
    }
    
    /**
     * 计算信号质量
     */
    fun calculateSignalQuality(packet: SensorData): Float {
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) return 0.0f
        
        try {
            // 获取第一个通道的数据进行质量评估
            val channelData = packet.getChannelData()
            if (channelData != null && channelData.isNotEmpty()) {
                val firstChannel = channelData[0]
                if (firstChannel != null) {
                    val signal = firstChannel.toFloatArray()
                    val quality = streamingSignalProcessor!!.calculateSignalQuality(signal)
                    
                    // 添加调试信息
                    Log.d("DataManager", "信号质量计算: 通道0, 数据长度=${signal.size}, 质量=$quality")
                    return quality
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "计算信号质量时发生错误: ${e.message}")
        }
        
        return 0.0f
    }
    
    /**
     * 应用信号处理
     */
    fun applySignalProcessing(packets: List<SensorData>): List<SensorData> {
        Log.d("DataManager", "开始应用信号处理，处理 ${packets.size} 个数据包")
        
        ensureStreamingSignalProcessor()
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) {
            Log.w("DataManager", "流式信号处理器未初始化，跳过信号处理")
            return packets
        }
        
        val processedPackets = mutableListOf<SensorData>()
        
        for (packet in packets) {
            try {
                val processedPacket = processSinglePacket(packet)
                processedPackets.add(processedPacket)
            } catch (e: Exception) {
                Log.e("DataManager", "处理数据包时发生错误: ${e.message}")
                processedPackets.add(packet) // 处理失败时返回原始数据包
            }
        }
        
        Log.d("DataManager", "信号处理完成，处理了 ${processedPackets.size} 个数据包")
        return processedPackets
    }
    
    /**
     * 处理单个数据包
     */
    private fun processSinglePacket(packet: SensorData): SensorData {
        val channelData = packet.getChannelData()
        if (channelData == null || channelData.isEmpty()) {
            return packet
        }
        
        val processedChannels = mutableListOf<List<Float>>()
        
        for (channel in channelData) {
            val processedChannel = when (packet.getDataType()) {
                type.SensorData.DataType.EEG -> applyEEGFilters(channel)
                type.SensorData.DataType.ECG_2LEAD, type.SensorData.DataType.ECG_12LEAD -> applyECGFilters(channel)
                type.SensorData.DataType.PPG -> channel // PPG不进行滤波处理，直接返回原始数据
                else -> channel // 其他类型暂时不处理
            }
            processedChannels.add(processedChannel)
        }
        
        // 创建处理后的数据包
        val processedPacket = SensorData()
        processedPacket.setDataType(packet.getDataType())
        processedPacket.setTimestamp(packet.getTimestamp())
        processedPacket.setPacketSn(packet.getPacketSn())
        processedPacket.setChannelData(processedChannels)
        
        return processedPacket
    }
    
    /**
     * 应用EEG滤波器
     */
    private fun applyEEGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
                // 1. 带通滤波 (1-40Hz，EEG主要频率范围)
                val bandpassFiltered = streamingSignalProcessor!!.bandpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                1.0f, 
                40.0f
            )
            
                if (bandpassFiltered != null) {
                    // 2. 幅度归一化
                    val normalized = streamingSignalProcessor!!.normalizeAmplitude(bandpassFiltered)
                    
                    if (normalized != null) {
                        return normalized.toList()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "EEG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 应用ECG滤波器
     */
    private fun applyECGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
            // 1. 高通滤波 (0.5Hz，去除基线漂移)
                val highpassFiltered = streamingSignalProcessor!!.highpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                0.5f
            )
            
                if (highpassFiltered != null) {
                // 2. 低通滤波 (40Hz，去除高频噪声)
                    val lowpassFiltered = streamingSignalProcessor!!.lowpassFilter(
                        highpassFiltered, 
                    filterSettings.sampleRate.toFloat(), 
                    40.0f
                )
                
                if (lowpassFiltered != null) {
                    // 3. 陷波滤波 (50Hz，去除工频干扰)
                        val notchFiltered = streamingSignalProcessor!!.notchFilter(
                        lowpassFiltered, 
                        filterSettings.sampleRate.toFloat(), 
                        50.0f,
                        10.0f
                    )
                    
                    if (notchFiltered != null) {
                        return notchFiltered.toList()
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "ECG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 清理缓冲区
     */
    fun cleanupBuffer() {
        try {
            // 清理原始数据包缓冲区，保留最新的100个数据包
            val maxKeepPackets = 100
            if (packetBuffer.size > maxKeepPackets) {
                val toRemove = packetBuffer.size - maxKeepPackets
                repeat(toRemove) {
                    if (packetBuffer.isNotEmpty()) {
                        packetBuffer.removeAt(0)
                    }
                }
                Log.d("DataManager", "清理了 $toRemove 个旧数据包，保留 $maxKeepPackets 个最新数据包")
            }
            
            // 清理处理后数据包缓冲区，保留最新的50个数据包
            val maxKeepProcessedPackets = 50
            if (processedPackets.size > maxKeepProcessedPackets) {
                val toRemove = processedPackets.size - maxKeepProcessedPackets
                repeat(toRemove) {
                    if (processedPackets.isNotEmpty()) {
                        processedPackets.removeAt(0)
                    }
                }
                Log.d("DataManager", "清理了 $toRemove 个旧处理后数据包，保留 $maxKeepProcessedPackets 个最新数据包")
            }
            
        } catch (e: Exception) {
            Log.e("DataManager", "清理缓冲区时发生错误: ${e.message}")
        }
    }
    
    
    
    /**
     * 应用PPG滤波器
     */
    private fun applyPPGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
            // 1. 低通滤波 (8Hz，PPG主要频率范围)
                val filtered = streamingSignalProcessor!!.lowpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                8.0f
            )
            
            if (filtered != null) {
                // 2. 去运动伪影
                    val motionArtifactRemoved = streamingSignalProcessor!!.processRealtimeChunk(
                    filtered, 
                    filterSettings.sampleRate.toFloat()
                )
                
                if (motionArtifactRemoved != null) {
                    return motionArtifactRemoved.toList()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "PPG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 设置滤波器参数
     */
    fun setFilterSettings(settings: FilterSettings) {
        try {
            filterSettings = settings
            Log.d("DataManager", "滤波器设置已更新: $settings")
        } catch (e: Exception) {
            Log.e("DataManager", "设置滤波器参数失败: ${e.message}")
        }
    }
    
    /**
     * 获取当前滤波器设置
     */
    fun getFilterSettings(): FilterSettings {
        return filterSettings
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            if (parserHandle != 0L) {
                try {
                    nativeCallback.destroyStreamParser(parserHandle)
                    Log.d("DataManager", "JNI解析器销毁成功")
                } catch (e: Exception) {
                    Log.e("DataManager", "JNI解析器销毁失败: ${e.message}", e)
                } finally {
                    parserHandle = 0L
                }
            }
            
            // 清理缓冲区
            packetBuffer.clear()
            mappedPacketBuffer.clear() // 清理映射后的数据包缓冲区
            processedPackets.clear()
            calculatedMetrics.clear()
            channelBuffers.clear()
            processedChannelBuffers.clear()
            rawStream.reset()
            
            // 重置状态
            totalPacketsParsed = 0L
            currentDataType = null
            lastProcessTime = 0L
            totalProcessedSamples = 0L
            
            // 清理回调列表
            additionalCallbacks.clear()
            
            Log.d("DataManager", "资源清理完成")
        } catch (e: Exception) {
            Log.e("DataManager", "清理资源时发生错误: ${e.message}")
        }
    }
    
    /**
     * 轻量级清理 - 只清理缓冲区，不销毁解析器
     */
    fun lightCleanup() {
        try {
            // 只清理缓冲区，保持解析器运行
            packetBuffer.clear()
            mappedPacketBuffer.clear()
            processedPackets.clear()
            calculatedMetrics.clear()
            channelBuffers.clear()
            processedChannelBuffers.clear()
            rawStream.reset()
            
            Log.d("DataManager", "轻量级清理完成，解析器保持运行")
        } catch (e: Exception) {
            Log.e("DataManager", "轻量级清理时发生错误: ${e.message}", e)
        }
    }
    
    /**
     * 获取映射后的数据包缓冲区
     */
    fun getMappedPacketBuffer(): List<SensorData> {
        return mappedPacketBuffer.toList()
    }
}
