package com.example.cmake_project_test

import android.util.Log
import type.SensorData

/**
 * 完整数据处理管道示例
 * 演示从原始数据到最终指标的完整流程
 */
class CompletePipelineExample {
    
    private val dataMapper = DataMapper()
    private val indicatorCalculator = IndicatorCalculator()
    private val signalProcessor = SignalProcessorJNI()
    
    private var dataMapperInitialized = false
    private var indicatorCalculatorInitialized = false
    private var signalProcessorInitialized = false
    
    /**
     * 初始化完整管道
     */
    fun initialize(): Boolean {
        Log.d("CompletePipeline", "初始化完整数据处理管道...")
        
        // 初始化数据映射器
        dataMapperInitialized = dataMapper.initialize()
        if (!dataMapperInitialized) {
            Log.e("CompletePipeline", "数据映射器初始化失败")
            return false
        }
        
        // 初始化指标计算器
        indicatorCalculatorInitialized = indicatorCalculator.initialize()
        if (!indicatorCalculatorInitialized) {
            Log.e("CompletePipeline", "指标计算器初始化失败")
            cleanup()
            return false
        }
        
        // 初始化信号处理器
        try {
            signalProcessorInitialized = signalProcessor.createProcessor()
            if (!signalProcessorInitialized) {
                Log.e("CompletePipeline", "信号处理器初始化失败")
                cleanup()
                return false
            }
        } catch (e: Exception) {
            Log.e("CompletePipeline", "信号处理器初始化异常: ${e.message}")
            cleanup()
            return false
        }
        
        Log.d("CompletePipeline", "完整数据处理管道初始化成功")
        return true
    }
    
    /**
     * 处理单个数据包的完整流程
     * 原始数据 → 解析数据 → 通道映射 → 信号处理 → 指标计算
     */
    fun processCompletePipeline(rawData: SensorData, sampleRate: Float = 250.0f): Map<String, Float>? {
        if (!isInitialized()) {
            Log.w("CompletePipeline", "管道未初始化")
            return null
        }
        
        Log.d("CompletePipeline", "开始处理完整数据管道...")
        Log.d("CompletePipeline", "输入数据类型: ${rawData.dataType}, 采样率: $sampleRate Hz")
        
        try {
            // 步骤1: 通道映射
            Log.d("CompletePipeline", "步骤1: 执行通道映射...")
            val mappedData = dataMapper.mapSensorData(rawData)
            if (mappedData == null) {
                Log.e("CompletePipeline", "通道映射失败")
                return null
            }
            Log.d("CompletePipeline", "通道映射完成")
            
            // 步骤2: 信号处理 (这里可以添加信号处理逻辑)
            Log.d("CompletePipeline", "步骤2: 执行信号处理...")
            // 暂时跳过信号处理，直接使用映射后的数据
            val processedData = mappedData
            Log.d("CompletePipeline", "信号处理完成")
            
            // 步骤3: 指标计算
            Log.d("CompletePipeline", "步骤3: 执行指标计算...")
            val metrics = indicatorCalculator.processCompletePipeline(processedData, sampleRate)
            if (metrics == null) {
                Log.e("CompletePipeline", "指标计算失败")
                return null
            }
            
            Log.d("CompletePipeline", "指标计算完成，计算了 ${metrics.size} 个指标")
            Log.d("CompletePipeline", "完整数据处理管道执行成功")
            
            // 打印主要指标
            metrics["heart_rate"]?.let { 
                Log.d("CompletePipeline", "心率: ${String.format("%.1f", it)} bpm") 
            }
            metrics["signal_quality"]?.let { 
                Log.d("CompletePipeline", "信号质量: ${String.format("%.2f", it)}") 
            }
            metrics["spo2"]?.let { 
                Log.d("CompletePipeline", "血氧饱和度: ${String.format("%.1f", it)}%") 
            }
            
            return metrics
            
        } catch (e: Exception) {
            Log.e("CompletePipeline", "完整数据处理管道异常: ${e.message}")
            return null
        }
    }
    
    /**
     * 批量处理数据包
     */
    fun processBatchPipeline(rawDataList: List<SensorData>, sampleRate: Float = 250.0f): List<Map<String, Float>> {
        if (!isInitialized()) {
            Log.w("CompletePipeline", "管道未初始化")
            return emptyList()
        }
        
        Log.d("CompletePipeline", "开始批量处理 ${rawDataList.size} 个数据包...")
        
        val results = mutableListOf<Map<String, Float>>()
        var successCount = 0
        
        for ((index, rawData) in rawDataList.withIndex()) {
            val metrics = processCompletePipeline(rawData, sampleRate)
            if (metrics != null) {
                results.add(metrics)
                successCount++
            } else {
                results.add(emptyMap())
            }
            
            // 每处理100个数据包打印一次进度
            if ((index + 1) % 100 == 0) {
                Log.d("CompletePipeline", "已处理 ${index + 1}/${rawDataList.size} 个数据包")
            }
        }
        
        Log.d("CompletePipeline", "批量处理完成: 成功 $successCount/${rawDataList.size} 个数据包")
        return results
    }
    
    /**
     * 检查管道是否已初始化
     */
    fun isInitialized(): Boolean {
        return dataMapperInitialized && indicatorCalculatorInitialized && signalProcessorInitialized
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            if (dataMapperInitialized) {
                // 使用公共方法或直接设置为false
                dataMapperInitialized = false
            }
            
            if (indicatorCalculatorInitialized) {
                // 使用公共方法或直接设置为false
                indicatorCalculatorInitialized = false
            }
            
            if (signalProcessorInitialized) {
                signalProcessor.destroyProcessor()
                signalProcessorInitialized = false
            }
            
            Log.d("CompletePipelineExample", "资源清理完成")
        } catch (e: Exception) {
            Log.e("CompletePipelineExample", "资源清理异常: ${e.message}")
        }
    }
}
