package com.example.cmake_project_test

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import java.util.UUID

/**
 * 蓝牙管理器
 * 负责蓝牙设备连接、数据接收和状态管理
 */
class BluetoothManager(private val context: Context) {
    
    companion object {
        private const val TAG = "BluetoothManager"
        
        // 常见的ECG设备UUID列表
        private val SERVICE_UUIDS = listOf(
            UUID.fromString("6e400001-b5a3-f393-e0a9-68716563686f"), // Nordic UART Service (NUS) - 你的设备
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"), // 默认
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"), // 常见变体1
            UUID.fromString("0000ffe5-0000-1000-8000-00805f9b34fb"), // 常见变体2
            UUID.fromString("0000ff00-0000-1000-8000-00805f9b34fb"), // 常见变体3
            UUID.fromString("0000ff10-0000-1000-8000-00805f9b34fb"), // 常见变体4
            UUID.fromString("0000ff20-0000-1000-8000-00805f9b34fb"), // 常见变体5
            UUID.fromString("0000ff30-0000-1000-8000-00805f9b34fb"), // 常见变体6
            UUID.fromString("0000ff40-0000-1000-8000-00805f9b34fb"), // 常见变体7
            UUID.fromString("0000ff50-0000-1000-8000-00805f9b34fb"), // 常见变体8
            UUID.fromString("0000ff60-0000-1000-8000-00805f9b34fb"), // 常见变体9
            UUID.fromString("0000ff70-0000-1000-8000-00805f9b34fb"), // 常见变体10
            UUID.fromString("0000ff80-0000-1000-8000-00805f9b34fb"), // 常见变体11
            UUID.fromString("0000ff90-0000-1000-8000-00805f9b34fb"), // 常见变体12
            UUID.fromString("0000ffa0-0000-1000-8000-00805f9b34fb"), // 常见变体13
            UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb")  // 常见变体14
        )
        
        private val CHARACTERISTIC_UUIDS = listOf(
            UUID.fromString("6e400002-b5a3-f393-e0a9-68716563686f"), // Nordic UART TX Characteristic - 你的设备
            UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"), // 默认
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"), // 常见变体1
            UUID.fromString("0000ffe6-0000-1000-8000-00805f9b34fb"), // 常见变体2
            UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb"), // 常见变体3
            UUID.fromString("0000ff11-0000-1000-8000-00805f9b34fb"), // 常见变体4
            UUID.fromString("0000ff21-0000-1000-8000-00805f9b34fb"), // 常见变体5
            UUID.fromString("0000ff31-0000-1000-8000-00805f9b34fb"), // 常见变体6
            UUID.fromString("0000ff41-0000-1000-8000-00805f9b34fb"), // 常见变体7
            UUID.fromString("0000ff51-0000-1000-8000-00805f9b34fb"), // 常见变体8
            UUID.fromString("0000ff61-0000-1000-8000-00805f9b34fb"), // 常见变体9
            UUID.fromString("0000ff71-0000-1000-8000-00805f9b34fb"), // 常见变体10
            UUID.fromString("0000ff81-0000-1000-8000-00805f9b34fb"), // 常见变体11
            UUID.fromString("0000ff91-0000-1000-8000-00805f9b34fb"), // 常见变体12
            UUID.fromString("0000ffa1-0000-1000-8000-00805f9b34fb"), // 常见变体13
            UUID.fromString("0000ffb1-0000-1000-8000-00805f9b34fb")  // 常见变体14
        )
        
        // 设备名称前缀 (根据你的设备调整)
        private const val DEVICE_NAME_PREFIX = "ECG"
    }
    
    private var bluetoothManager: BluetoothManager? = null
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothGatt: BluetoothGatt? = null
    private var bluetoothLeScanner: BluetoothLeScanner? = null
    
    // 连接状态
    private var isConnected = false
    private var isConnecting = false
    
    // 设备列表
    private val discoveredDevices = mutableListOf<BluetoothDevice>()
    
    // 回调接口
    interface BluetoothCallback {
        fun onDeviceFound(device: BluetoothDevice)
        fun onConnected(device: BluetoothDevice)
        fun onDisconnected()
        fun onDataReceived(data: ByteArray)
        fun onError(message: String)
        fun onStatusChanged(status: String)
        fun onScanComplete(devices: List<BluetoothDevice>)
    }
    
    private var callback: BluetoothCallback? = null
    
    init {
        initializeBluetooth()
    }
    
    /**
     * 初始化蓝牙
     */
    private fun initializeBluetooth() {
        try {
            bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
            bluetoothAdapter = bluetoothManager?.adapter
            
            if (bluetoothAdapter == null) {
                Log.e(TAG, "设备不支持蓝牙")
                callback?.onError("设备不支持蓝牙")
                return
            }
            
            if (!bluetoothAdapter!!.isEnabled) {
                Log.w(TAG, "蓝牙未启用")
                callback?.onStatusChanged("蓝牙未启用，请先启用蓝牙")
                return
            }
            
            // 初始化BLE扫描器
            bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
            
            if (bluetoothLeScanner == null) {
                Log.w(TAG, "设备不支持BLE")
                callback?.onStatusChanged("设备不支持BLE，将使用传统蓝牙扫描")
            }
            
            Log.d(TAG, "蓝牙初始化成功")
            callback?.onStatusChanged("蓝牙已就绪")
            
        } catch (e: Exception) {
            Log.e(TAG, "蓝牙初始化失败: ${e.message}")
            callback?.onError("蓝牙初始化失败: ${e.message}")
        }
    }
    
    /**
     * 设置回调
     */
    fun setCallback(callback: BluetoothCallback) {
        this.callback = callback
    }
    
    /**
     * 扫描蓝牙设备
     */
    fun startScan() {
        if (bluetoothAdapter == null) {
            callback?.onError("蓝牙未初始化")
            return
        }
        
        if (!bluetoothAdapter!!.isEnabled) {
            callback?.onError("蓝牙未启用")
            return
        }
        
        try {
            // 清空之前的设备列表
            discoveredDevices.clear()
            callback?.onStatusChanged("正在扫描蓝牙设备...")
            
            // 检查所有必要权限
            val missingPermissions = mutableListOf<String>()
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_SCAN")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_CONNECT")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("ACCESS_FINE_LOCATION")
            }
            
            if (missingPermissions.isNotEmpty()) {
                callback?.onError("缺少权限: ${missingPermissions.joinToString(", ")}")
                return
            }
            
            // 优先使用BLE扫描
            if (bluetoothLeScanner != null) {
                startBleScan()
            } else {
                // 回退到传统蓝牙扫描
                startClassicScan()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "扫描失败: ${e.message}")
            callback?.onError("扫描失败: ${e.message}")
        }
    }
    
    /**
     * 开始BLE扫描
     */
    private fun startBleScan() {
        try {
            val scanSettings = ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build()
            
            bluetoothLeScanner?.startScan(null, scanSettings, bleScanCallback)
            Log.d(TAG, "BLE扫描已开始")
            
            // 10秒后停止扫描
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                stopBleScan()
            }, 10000)
            
        } catch (e: Exception) {
            Log.e(TAG, "BLE扫描失败: ${e.message}")
            callback?.onError("BLE扫描失败: ${e.message}")
        }
    }
    
    /**
     * 开始传统蓝牙扫描
     */
    private fun startClassicScan() {
        try {
            registerClassicScanReceiver()
            bluetoothAdapter?.startDiscovery()
            Log.d(TAG, "传统蓝牙扫描已开始")
            
            // 10秒后停止扫描
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                stopClassicScan()
            }, 10000)
            
        } catch (e: Exception) {
            Log.e(TAG, "传统蓝牙扫描失败: ${e.message}")
            callback?.onError("传统蓝牙扫描失败: ${e.message}")
        }
    }
    
    /**
     * 停止扫描
     */
    fun stopScan() {
        try {
            stopBleScan()
            stopClassicScan()
            callback?.onStatusChanged("扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止扫描失败: ${e.message}")
        }
    }
    
    /**
     * 停止BLE扫描
     */
    private fun stopBleScan() {
        try {
            bluetoothLeScanner?.stopScan(bleScanCallback)
            Log.d(TAG, "BLE扫描已停止")
            
            // 扫描完成后立即触发回调
            callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
            callback?.onScanComplete(discoveredDevices.toList())
        } catch (e: Exception) {
            Log.e(TAG, "停止BLE扫描失败: ${e.message}")
        }
    }
    
    /**
     * 停止传统蓝牙扫描
     */
    private fun stopClassicScan() {
        try {
            bluetoothAdapter?.cancelDiscovery()
            unregisterClassicScanReceiver()
            Log.d(TAG, "传统蓝牙扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止传统蓝牙扫描失败: ${e.message}")
        }
    }
    
    /**
     * 连接设备
     */
    fun connectToDevice(device: BluetoothDevice) {
        if (isConnecting || isConnected) {
            callback?.onError("正在连接或已连接")
            return
        }
        
        try {
            isConnecting = true
            callback?.onStatusChanged("正在连接设备: ${device.name}")
            
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onError("缺少蓝牙连接权限")
                isConnecting = false
                return
            }
            
            // 连接设备
            bluetoothGatt = device.connectGatt(context, false, gattCallback)
            
        } catch (e: Exception) {
            Log.e(TAG, "连接失败: ${e.message}")
            callback?.onError("连接失败: ${e.message}")
            isConnecting = false
        }
    }
    
    /**
     * 断开连接
     */
    fun disconnect() {
        try {
            bluetoothGatt?.disconnect()
            bluetoothGatt?.close()
            bluetoothGatt = null
            isConnected = false
            isConnecting = false
            callback?.onStatusChanged("已断开连接")
        } catch (e: Exception) {
            Log.e(TAG, "断开连接失败: ${e.message}")
        }
    }
    
    /**
     * GATT回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Log.d(TAG, "设备已连接")
                    isConnected = true
                    isConnecting = false
                    callback?.onConnected(gatt.device)
                    callback?.onStatusChanged("设备已连接")
                    
                    // 发现服务
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices()
                    }
                }
                BluetoothProfile.STATE_DISCONNECTED -> {
                    Log.d(TAG, "设备已断开")
                    isConnected = false
                    isConnecting = false
                    callback?.onDisconnected()
                    callback?.onStatusChanged("设备已断开")
                }
            }
        }
        
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功")
                callback?.onStatusChanged("服务发现成功")
                
                // 打印所有可用服务
                val services = gatt.services
                Log.d(TAG, "设备提供的服务数量: ${services.size}")
                
                for (service in services) {
                    Log.d(TAG, "发现服务: ${service.uuid}")
                    callback?.onStatusChanged("发现服务: ${service.uuid}")
                    
                    // 打印服务的所有特征
                    val characteristics = service.characteristics
                    Log.d(TAG, "服务 ${service.uuid} 的特征数量: ${characteristics.size}")
                    
                    for (characteristic in characteristics) {
                        Log.d(TAG, "发现特征: ${characteristic.uuid}")
                        callback?.onStatusChanged("发现特征: ${characteristic.uuid}")
                    }
                }
                
                // 尝试查找匹配的服务和特征
                var foundService: BluetoothGattService? = null
                var foundCharacteristic: BluetoothGattCharacteristic? = null
                
                // 首先尝试预设的UUID列表
                for (serviceUuid in SERVICE_UUIDS) {
                    val service = gatt.getService(serviceUuid)
                    if (service != null) {
                        Log.d(TAG, "找到匹配的服务: $serviceUuid")
                        foundService = service
                        
                        // 查找匹配的特征
                        for (characteristicUuid in CHARACTERISTIC_UUIDS) {
                            val characteristic = service.getCharacteristic(characteristicUuid)
                            if (characteristic != null) {
                                Log.d(TAG, "找到匹配的特征: $characteristicUuid")
                                foundCharacteristic = characteristic
                                break
                            }
                        }
                        break
                    }
                }
                
                // 如果预设UUID没有找到，尝试智能检测
                if (foundService == null || foundCharacteristic == null) {
                    Log.d(TAG, "预设UUID未找到匹配，尝试智能检测")
                    
                    // 查找所有非标准蓝牙服务的UUID
                    for (service in services) {
                        val serviceUuid = service.uuid.toString()
                        
                        // 跳过标准蓝牙服务（如2a00, 2a01等）
                        if (!serviceUuid.contains("00002a") && !serviceUuid.contains("000018")) {
                            Log.d(TAG, "发现自定义服务: $serviceUuid")
                            
                            // 查找该服务下的所有特征
                            for (characteristic in service.characteristics) {
                                val characteristicUuid = characteristic.uuid.toString()
                                
                                // 跳过标准特征
                                if (!characteristicUuid.contains("00002a")) {
                                    Log.d(TAG, "发现自定义特征: $characteristicUuid")
                                    
                                    // 检查特征是否支持通知
                                    if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 ||
                                        characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) {
                                        
                                        Log.d(TAG, "找到支持通知的特征: $characteristicUuid")
                                        foundService = service
                                        foundCharacteristic = characteristic
                                        break
                                    }
                                }
                            }
                            if (foundService != null) break
                        }
                    }
                }
                
                if (foundService != null && foundCharacteristic != null) {
                    // 启用通知
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "=== 启用特征通知 ===")
                        Log.d(TAG, "服务UUID: ${foundService.uuid}")
                        Log.d(TAG, "特征UUID: ${foundCharacteristic.uuid}")
                        Log.d(TAG, "特征属性: ${foundCharacteristic.properties}")
                        
                        val success = gatt.setCharacteristicNotification(foundCharacteristic, true)
                        Log.d(TAG, "启用特征通知结果: $success")
                        
                        callback?.onStatusChanged("数据通道已建立，开始接收数据")
                    } else {
                        Log.e(TAG, "缺少BLUETOOTH_CONNECT权限")
                        callback?.onError("缺少BLUETOOTH_CONNECT权限")
                    }
                } else {
                    Log.e(TAG, "未找到匹配的服务或特征")
                    callback?.onError("未找到匹配的服务或特征，请检查设备协议")
                    
                    // 提供所有可用服务的UUID供参考
                    val availableServices = services.joinToString(", ") { it.uuid.toString() }
                    Log.d(TAG, "可用服务UUID: $availableServices")
                    callback?.onStatusChanged("可用服务: $availableServices")
                }
            } else {
                Log.e(TAG, "服务发现失败，状态: $status")
                callback?.onError("服务发现失败，状态: $status")
            }
        }
        
        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            // 接收数据
            val data = characteristic.value
            Log.d(TAG, "=== 蓝牙特征值变化 ===")
            Log.d(TAG, "特征UUID: ${characteristic.uuid}")
            Log.d(TAG, "接收到数据: ${data.size} 字节")
            if (data.isNotEmpty()) {
                Log.d(TAG, "数据前10字节: ${data.take(10).joinToString(", ") { "0x%02X".format(it) }}")
            }
            callback?.onDataReceived(data)
        }
    }
    
    /**
     * BLE扫描回调
     */
    private val bleScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            
            val device = result.device
            Log.d(TAG, "发现BLE设备: ${device.name ?: "未知"} (${device.address})")
            
            // 添加所有发现的设备（不进行过滤）
            addDiscoveredDevice(device)
            callback?.onDeviceFound(device)
        }
        
        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.e(TAG, "BLE扫描失败，错误码: $errorCode")
            callback?.onError("BLE扫描失败，错误码: $errorCode")
            
            // 扫描失败时完成扫描
            callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
            callback?.onScanComplete(discoveredDevices.toList())
        }
    }
    
    /**
     * 传统蓝牙扫描回调
     */
    private val classicScanReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: android.content.Intent?) {
            when (intent?.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {
                        Log.d(TAG, "发现传统蓝牙设备: ${it.name ?: "未知"} (${it.address})")
                        
                        // 添加所有发现的设备（不进行过滤）
                        addDiscoveredDevice(it)
                        callback?.onDeviceFound(it)
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    Log.d(TAG, "传统蓝牙扫描开始")
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    Log.d(TAG, "传统蓝牙扫描完成")
                    callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
                    callback?.onScanComplete(discoveredDevices.toList())
                }
            }
        }
    }
    
    /**
     * 注册传统蓝牙扫描广播接收器
     */
    private fun registerClassicScanReceiver() {
        val filter = android.content.IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        }
        context.registerReceiver(classicScanReceiver, filter)
    }
    
    /**
     * 注销传统蓝牙扫描广播接收器
     */
    private fun unregisterClassicScanReceiver() {
        try {
            context.unregisterReceiver(classicScanReceiver)
        } catch (e: Exception) {
            Log.e(TAG, "注销广播接收器失败: ${e.message}")
        }
    }
    
    /**
     * 添加发现的设备
     */
    fun addDiscoveredDevice(device: BluetoothDevice) {
        if (!discoveredDevices.contains(device)) {
            discoveredDevices.add(device)
            callback?.onDeviceFound(device)
        }
    }
    
    /**
     * 获取发现的设备列表
     */
    fun getDiscoveredDevices(): List<BluetoothDevice> {
        return discoveredDevices.toList()
    }
    
    /**
     * 获取连接状态
     */
    fun isConnected(): Boolean = isConnected
    
    /**
     * 获取连接中状态
     */
    fun isConnecting(): Boolean = isConnecting
    
    /**
     * 清理资源
     */
    fun cleanup() {
        disconnect()
        stopScan()
        unregisterClassicScanReceiver()
    }
}
