package com.xyzshell.andinfo.libs

import android.Manifest
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraMetadata
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Range
import android.util.SizeF
import com.xyzshell.andinfo.R
import com.xyzshell.andinfo.libs.camera.models.CameraCapability
import com.xyzshell.andinfo.libs.camera.models.CameraFacing
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlin.math.sqrt

/**
 * 摄像头信息工具类
 * 提供摄像头硬件参数、特性、功能列表等详细信息
 * 需要权限: CAMERA
 */
class CameraInfo(private val context: Context) {

    /**
     * 摄像头管理器
     */
    private val cameraManager: CameraManager? = context.getSystemService(
        CameraManager::class.java
    )

    /**
     * 摄像头详细信息数据类
     */
    data class CameraDetails(
        val cameraId: String,                          // 摄像头ID
        val facing: CameraFacing?,                     // 前置/后置/外置
        val facingText: String,                        // 方向文本

        // 传感器信息
        val megaPixels: Double?,                       // 有效百万像素
        val resolution: String?,                       // 分辨率（宽x高）
        val sensorSize: String?,                       // 传感器尺寸（mm）
        val sensorSizeInch: Double?,                   // 传感器英寸
        val pixelSize: Double?,                        // 单像素尺寸（μm）
        val colorFilterArrangement: String?,           // 滤镜颜色排列（Bayer等）

        // 光学参数
        val focalLength: FloatArray?,                  // 焦距（mm）
        val apertures: FloatArray?,                    // 光圈值
        val fieldOfView: String?,                      // 视野角度
        val focal35mmEquivalent: Double?,              // 35mm等效焦距
        val cropFactor: Double?,                       // 裁切系数

        // 曝光参数
        val isoRange: Range<Int>?,                     // ISO感光范围
        val exposureTimeRange: Range<Long>?,           // 曝光时间范围（纳秒）
        val shutterSpeedRange: String?,                // 快门速度范围
        val exposureCompensationRange: String?,        // 曝光补偿范围
        val exposureCompensationStep: Double?,         // 曝光补偿步长

        // 对焦参数
        val minimumFocusDistance: Float?,              // 最小对焦距离（屈光度）
        val minimumFocusDistanceCm: Double?,           // 最小对焦距离（厘米）
        val hyperFocalDistance: Float?,                // 超焦距

        // 功能特性
        val hasFlash: Boolean?,                        // 是否有闪光灯
        val hasOpticalStabilization: Boolean?,         // 光学防抖（OIS）
        val hasVideoStabilization: Boolean?,           // 视频防抖
        val hasAutoFocus: Boolean?,                    // 自动对焦
        val camera2ApiSupport: String?,                // Camera2 API支持级别

        // 面部检测
        val maxFaceCount: Int?,                        // 最大面部检测数量
        val faceDetectionModes: List<String>?,         // 面部检测模式列表

        // 功能列表
        val capabilities: List<CameraCapability>,      // 摄像头能力
        val supportedFeatures: List<String>,           // 支持的功能（HDR、RAW等）

        // 模式列表
        val autoExposureModes: List<String>?,          // 自动曝光模式
        val autoFocusModes: List<String>?,             // 自动对焦模式
        val whiteBalanceModes: List<String>?,          // 白平衡模式
        val sceneModes: List<String>?,                 // 场景模式
        val colorEffects: List<String>?,               // 色彩效果

        // 视频能力
        val maxFrameRate: Int?,                        // 最大帧率
        val supportsHighSpeedVideo: Boolean,           // 是否支持高速视频
        val supports4K: Boolean,                       // 是否支持4K录制
        val supports8K: Boolean                        // 是否支持8K录制
    )

    /**
     * 获取所有摄像头ID列表
     */
    val cameraIds: List<String>
        get() = cameraManager?.cameraIdList?.toList() ?: emptyList()

    /**
     * 获取指定摄像头的特性对象
     * @param cameraId 摄像头ID
     * @return CameraCharacteristics 对象
     */
    fun getCameraCharacteristics(cameraId: String): CameraCharacteristics? {
        return cameraManager?.getCameraCharacteristics(cameraId)
    }

    /**
     * 监听摄像头可用性变化的 Flow
     */
    fun cameraIdsFlow() = cameraManager?.let { manager ->
        callbackFlow {
            val onCameraIdUpdated = {
                trySend(manager.cameraIdList.toList())
            }

            val availabilityCallback = object : CameraManager.AvailabilityCallback() {
                override fun onCameraAvailable(cameraId: String) {
                    onCameraIdUpdated()
                }

                override fun onCameraUnavailable(cameraId: String) {
                    onCameraIdUpdated()
                }
            }

            manager.registerAvailabilityCallback(
                availabilityCallback, Handler(Looper.getMainLooper())
            )

            onCameraIdUpdated()

            awaitClose {
                manager.unregisterAvailabilityCallback(availabilityCallback)
            }
        }
    }

    // ==================== 基本信息 ====================

    /**
     * 获取摄像头朝向
     * @return 前置/后置/外置
     */
    fun getCameraFacing(characteristics: CameraCharacteristics): CameraFacing? {
        return characteristics.get(CameraCharacteristics.LENS_FACING)?.let {
            when (it) {
                CameraMetadata.LENS_FACING_BACK -> CameraFacing.BACK
                CameraMetadata.LENS_FACING_FRONT -> CameraFacing.FRONT
                CameraMetadata.LENS_FACING_EXTERNAL -> CameraFacing.EXTERNAL
                else -> null
            }
        }
    }

    /**
     * 获取摄像头朝向文本
     */
    fun getCameraFacingText(characteristics: CameraCharacteristics): String {
        return when (getCameraFacing(characteristics)) {
            CameraFacing.BACK -> "后置"
            CameraFacing.FRONT -> "前置"
            CameraFacing.EXTERNAL -> "外置"
            else -> "未知"
        }
    }

    // ==================== 传感器信息 ====================

    /**
     * 获取像素阵列尺寸（分辨率）
     * @return 格式: "宽x高"
     */
    fun getPixelArraySize(characteristics: CameraCharacteristics): String? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)?.toString()
    }

    /**
     * 获取有效百万像素
     */
    fun getMegaPixels(characteristics: CameraCharacteristics): Double? {
        val size = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)
        return size?.let { (it.width * it.height) / 1_000_000.0 }
    }

    /**
     * 获取传感器物理尺寸
     * @return 格式: "宽x高 mm"
     */
    fun getSensorPhysicalSize(characteristics: CameraCharacteristics): String? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)?.let {
            String.format("%.2f x %.2f mm", it.width, it.height)
        }
    }

    /**
     * 获取传感器尺寸（英寸，对角线）
     */
    fun getSensorSizeInch(characteristics: CameraCharacteristics): Double? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)?.let {
            val diagonal = sqrt((it.width * it.width + it.height * it.height).toDouble())
            diagonal / 25.4 // 转换为英寸
        }
    }

    /**
     * 获取单像素尺寸（微米）
     */
    fun getPixelSize(characteristics: CameraCharacteristics): Double? {
        val physicalSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)
        val pixelArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)

        return if (physicalSize != null && pixelArray != null) {
            val pixelWidth = (physicalSize.width * 1000) / pixelArray.width
            val pixelHeight = (physicalSize.height * 1000) / pixelArray.height
            (pixelWidth + pixelHeight) / 2.0
        } else null
    }

    /**
     * 获取滤镜颜色排列
     */
    fun getColorFilterArrangement(characteristics: CameraCharacteristics): String? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT)?.let {
            when (it) {
                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB -> "RGGB (Bayer)"
                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG -> "GRBG (Bayer)"
                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG -> "GBRG (Bayer)"
                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR -> "BGGR (Bayer)"
                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGB -> "RGB"
                5 -> "Mono/NIR (单色/近红外)" // MONO/NIR
                else -> "未知"
            }
        }
    }

    // ==================== 光学参数 ====================

    /**
     * 获取焦距数组
     */
    fun getFocalLength(characteristics: CameraCharacteristics): FloatArray? {
        return characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
    }

    /**
     * 获取光圈值数组
     */
    fun getAvailableApertures(characteristics: CameraCharacteristics): FloatArray? {
        return characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
    }

    /**
     * 获取35mm等效焦距
     */
    fun getFocal35mmEquivalent(characteristics: CameraCharacteristics): Double? {
        val focalLength = getFocalLength(characteristics)?.firstOrNull()
        val cropFactor = getCropFactor(characteristics)
        return if (focalLength != null && cropFactor != null) {
            focalLength * cropFactor
        } else null
    }

    /**
     * 获取裁切系数（相对于全画幅）
     */
    fun getCropFactor(characteristics: CameraCharacteristics): Double? {
        val sensorSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)
        return sensorSize?.let {
            val diagonal = sqrt((it.width * it.width + it.height * it.height).toDouble())
            43.27 / diagonal // 全画幅对角线约43.27mm
        }
    }

    /**
     * 获取视野角度
     */
    fun getFieldOfView(characteristics: CameraCharacteristics): String? {
        val focalLength = getFocalLength(characteristics)?.firstOrNull()
        val sensorSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)

        return if (focalLength != null && sensorSize != null) {
            val hFov = 2 * Math.toDegrees(Math.atan((sensorSize.width / 2.0 / focalLength).toDouble()))
            val vFov = 2 * Math.toDegrees(Math.atan((sensorSize.height / 2.0 / focalLength).toDouble()))
            String.format("H: %.1f°, V: %.1f°", hFov, vFov)
        } else null
    }

    // ==================== 曝光参数 ====================

    /**
     * 获取ISO感光度范围
     */
    fun getIsoRange(characteristics: CameraCharacteristics): Range<Int>? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE)
    }

    /**
     * 获取曝光时间范围（纳秒）
     */
    fun getExposureTimeRange(characteristics: CameraCharacteristics): Range<Long>? {
        return characteristics.get(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE)
    }

    /**
     * 获取快门速度范围（格式化字符串）
     */
    fun getShutterSpeedRange(characteristics: CameraCharacteristics): String? {
        val exposureRange = getExposureTimeRange(characteristics)
        return exposureRange?.let {
            val minSeconds = it.lower / 1_000_000_000.0
            val maxSeconds = it.upper / 1_000_000_000.0
            String.format("1/%.0f - %.2fs", 1.0 / minSeconds, maxSeconds)
        }
    }

    /**
     * 获取曝光补偿范围
     */
    fun getExposureCompensationRange(characteristics: CameraCharacteristics): String? {
        val range = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE)
        val step = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP)

        return if (range != null && step != null) {
            val minEv = range.lower * step.toDouble()
            val maxEv = range.upper * step.toDouble()
            String.format("%.1f ~ %.1f EV", minEv, maxEv)
        } else null
    }

    /**
     * 获取曝光补偿步长
     */
    fun getExposureCompensationStep(characteristics: CameraCharacteristics): Double? {
        return characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP)?.toDouble()
    }

    // ==================== 对焦参数 ====================

    /**
     * 获取最小对焦距离（屈光度）
     */
    fun getMinimumFocusDistance(characteristics: CameraCharacteristics): Float? {
        return characteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE)
    }

    /**
     * 获取最小对焦距离（厘米）
     */
    fun getMinimumFocusDistanceCm(characteristics: CameraCharacteristics): Double? {
        val diopters = getMinimumFocusDistance(characteristics)
        return diopters?.let {
            if (it > 0) 100.0 / it else null
        }
    }

    /**
     * 获取超焦距
     */
    fun getHyperFocalDistance(characteristics: CameraCharacteristics): Float? {
        return characteristics.get(CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE)
    }

    // ==================== 功能特性 ====================

    /**
     * 是否有闪光灯
     */
    fun hasFlashUnit(characteristics: CameraCharacteristics): Boolean? {
        return characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)
    }

    /**
     * 是否支持光学防抖（OIS）
     */
    fun hasOpticalStabilization(characteristics: CameraCharacteristics): Boolean {
        val modes = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION)
        return modes?.contains(CameraCharacteristics.LENS_OPTICAL_STABILIZATION_MODE_ON) == true
    }

    /**
     * 是否支持视频防抖
     */
    fun hasVideoStabilization(characteristics: CameraCharacteristics): Boolean {
        val modes = characteristics.get(CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES)
        return modes?.contains(CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_ON) == true
    }

    /**
     * 是否支持自动对焦
     */
    fun hasAutoFocus(characteristics: CameraCharacteristics): Boolean {
        val minDistance = getMinimumFocusDistance(characteristics)
        return minDistance != null && minDistance > 0
    }

    /**
     * 获取Camera2 API支持级别
     */
    fun getCamera2ApiSupport(characteristics: CameraCharacteristics): String? {
        return characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)?.let {
            when (it) {
                CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED -> "LIMITED"
                CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL -> "FULL"
                CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY -> "LEGACY"
                CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3 -> "LEVEL_3"
                CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "EXTERNAL" else "未知"
                else -> "未知"
            }
        }
    }

    // ==================== 面部检测 ====================

    /**
     * 获取最大面部检测数量
     */
    fun getMaxFaceCount(characteristics: CameraCharacteristics): Int? {
        return characteristics.get(CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT)
    }

    /**
     * 获取面部检测模式列表
     */
    fun getFaceDetectionModes(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES)?.map {
            when (it) {
                CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_OFF -> "关闭"
                CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE -> "简单"
                CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_FULL -> "完整"
                else -> "未知"
            }
        }
    }

    // ==================== 能力列表 ====================

    /**
     * 获取摄像头能力列表
     */
    fun getAvailableCapabilities(characteristics: CameraCharacteristics): List<CameraCapability> {
        val capabilities = characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)
        return capabilities?.toList()?.mapNotNull { capability ->
            when (capability) {
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE -> CameraCapability.BACKWARD_COMPATIBLE
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR -> CameraCapability.MANUAL_SENSOR
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING -> CameraCapability.MANUAL_POST_PROCESSING
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW -> CameraCapability.RAW
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING -> CameraCapability.PRIVATE_REPROCESSING
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS -> CameraCapability.READ_SENSOR_SETTINGS
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE -> CameraCapability.BURST_CAPTURE
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING -> CameraCapability.YUV_REPROCESSING
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DEPTH_OUTPUT -> CameraCapability.DEPTH_OUTPUT
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO -> CameraCapability.CONSTRAINED_HIGH_SPEED_VIDEO
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MOTION_TRACKING -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) CameraCapability.MOTION_TRACKING else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) CameraCapability.LOGICAL_MULTI_CAMERA else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) CameraCapability.MONOCHROME else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) CameraCapability.SECURE_IMAGE_DATA else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) CameraCapability.SYSTEM_CAMERA else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) CameraCapability.OFFLINE_PROCESSING else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) CameraCapability.ULTRA_HIGH_RESOLUTION_SENSOR else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_REMOSAIC_REPROCESSING -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) CameraCapability.REMOSAIC_REPROCESSING else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DYNAMIC_RANGE_TEN_BIT -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) CameraCapability.DYNAMIC_RANGE_TEN_BIT else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_STREAM_USE_CASE -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) CameraCapability.STREAM_USE_CASE else null
                CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_COLOR_SPACE_PROFILES -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) CameraCapability.COLOR_SPACE_PROFILES else null
                else -> null
            }
        } ?: emptyList()
    }

    /**
     * 获取支持的功能列表（人类可读）
     */
    fun getSupportedFeatures(characteristics: CameraCharacteristics): List<String> {
        val features = mutableListOf<String>()
        val capabilities = getAvailableCapabilities(characteristics)

        if (capabilities.contains(CameraCapability.RAW)) features.add("RAW拍摄")
        if (capabilities.contains(CameraCapability.BURST_CAPTURE)) features.add("连拍")
        if (capabilities.contains(CameraCapability.DEPTH_OUTPUT)) features.add("景深输出")
        if (capabilities.contains(CameraCapability.CONSTRAINED_HIGH_SPEED_VIDEO)) features.add("高速视频")
        if (capabilities.contains(CameraCapability.MANUAL_SENSOR)) features.add("手动模式")
        if (capabilities.contains(CameraCapability.MONOCHROME)) features.add("黑白模式")
        if (capabilities.contains(CameraCapability.ULTRA_HIGH_RESOLUTION_SENSOR)) features.add("超高分辨率")
        if (capabilities.contains(CameraCapability.DYNAMIC_RANGE_TEN_BIT)) features.add("10-bit HDR")

        if (hasOpticalStabilization(characteristics)) features.add("光学防抖")
        if (hasVideoStabilization(characteristics)) features.add("视频防抖")

        return features
    }

    // ==================== 模式列表 ====================

    /**
     * 获取自动曝光模式列表
     */
    fun getAutoExposureModes(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES)?.map {
            when (it) {
                CameraCharacteristics.CONTROL_AE_MODE_OFF -> "关闭"
                CameraCharacteristics.CONTROL_AE_MODE_ON -> "自动"
                CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH -> "自动闪光"
                CameraCharacteristics.CONTROL_AE_MODE_ON_ALWAYS_FLASH -> "强制闪光"
                CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE -> "防红眼"
                CameraCharacteristics.CONTROL_AE_MODE_ON_EXTERNAL_FLASH -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "外置闪光" else "未知"
                else -> "未知"
            }
        }
    }

    /**
     * 获取自动对焦模式列表
     */
    fun getAutoFocusModes(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES)?.map {
            when (it) {
                CameraCharacteristics.CONTROL_AF_MODE_OFF -> "关闭"
                CameraCharacteristics.CONTROL_AF_MODE_AUTO -> "自动"
                CameraCharacteristics.CONTROL_AF_MODE_MACRO -> "微距"
                CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_VIDEO -> "连续视频"
                CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_PICTURE -> "连续拍照"
                CameraCharacteristics.CONTROL_AF_MODE_EDOF -> "EDOF"
                else -> "未知"
            }
        }
    }

    /**
     * 获取白平衡模式列表
     */
    fun getWhiteBalanceModes(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES)?.map {
            when (it) {
                CameraCharacteristics.CONTROL_AWB_MODE_OFF -> "关闭"
                CameraCharacteristics.CONTROL_AWB_MODE_AUTO -> "自动"
                CameraCharacteristics.CONTROL_AWB_MODE_INCANDESCENT -> "白炽灯"
                CameraCharacteristics.CONTROL_AWB_MODE_FLUORESCENT -> "荧光灯"
                CameraCharacteristics.CONTROL_AWB_MODE_WARM_FLUORESCENT -> "暖荧光"
                CameraCharacteristics.CONTROL_AWB_MODE_DAYLIGHT -> "日光"
                CameraCharacteristics.CONTROL_AWB_MODE_CLOUDY_DAYLIGHT -> "阴天"
                CameraCharacteristics.CONTROL_AWB_MODE_TWILIGHT -> "黄昏"
                CameraCharacteristics.CONTROL_AWB_MODE_SHADE -> "阴影"
                else -> "未知"
            }
        }
    }

    /**
     * 获取场景模式列表
     */
    fun getSceneModes(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.CONTROL_AVAILABLE_SCENE_MODES)?.map {
            when (it) {
                CameraCharacteristics.CONTROL_SCENE_MODE_DISABLED -> "禁用"
                CameraCharacteristics.CONTROL_SCENE_MODE_FACE_PRIORITY -> "人像优先"
                CameraCharacteristics.CONTROL_SCENE_MODE_ACTION -> "运动"
                CameraCharacteristics.CONTROL_SCENE_MODE_PORTRAIT -> "人像"
                CameraCharacteristics.CONTROL_SCENE_MODE_LANDSCAPE -> "风景"
                CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT -> "夜景"
                CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT_PORTRAIT -> "夜景人像"
                CameraCharacteristics.CONTROL_SCENE_MODE_THEATRE -> "剧院"
                CameraCharacteristics.CONTROL_SCENE_MODE_BEACH -> "海滩"
                CameraCharacteristics.CONTROL_SCENE_MODE_SNOW -> "雪景"
                CameraCharacteristics.CONTROL_SCENE_MODE_SUNSET -> "日落"
                CameraCharacteristics.CONTROL_SCENE_MODE_STEADYPHOTO -> "防抖"
                CameraCharacteristics.CONTROL_SCENE_MODE_FIREWORKS -> "烟火"
                CameraCharacteristics.CONTROL_SCENE_MODE_SPORTS -> "体育"
                CameraCharacteristics.CONTROL_SCENE_MODE_PARTY -> "派对"
                CameraCharacteristics.CONTROL_SCENE_MODE_CANDLELIGHT -> "烛光"
                CameraCharacteristics.CONTROL_SCENE_MODE_BARCODE -> "条形码"
                CameraCharacteristics.CONTROL_SCENE_MODE_HIGH_SPEED_VIDEO -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) "高速视频" else "未知"
                CameraCharacteristics.CONTROL_SCENE_MODE_HDR -> "HDR"
                else -> "未知"
            }
        }
    }

    /**
     * 获取色彩效果列表
     */
    fun getColorEffects(characteristics: CameraCharacteristics): List<String>? {
        return characteristics.get(CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS)?.map {
            when (it) {
                CameraCharacteristics.CONTROL_EFFECT_MODE_OFF -> "关闭"
                CameraCharacteristics.CONTROL_EFFECT_MODE_MONO -> "黑白"
                CameraCharacteristics.CONTROL_EFFECT_MODE_NEGATIVE -> "负片"
                CameraCharacteristics.CONTROL_EFFECT_MODE_SOLARIZE -> "曝光"
                CameraCharacteristics.CONTROL_EFFECT_MODE_SEPIA -> "棕褐色"
                CameraCharacteristics.CONTROL_EFFECT_MODE_POSTERIZE -> "海报化"
                CameraCharacteristics.CONTROL_EFFECT_MODE_WHITEBOARD -> "白板"
                CameraCharacteristics.CONTROL_EFFECT_MODE_BLACKBOARD -> "黑板"
                CameraCharacteristics.CONTROL_EFFECT_MODE_AQUA -> "水蓝"
                else -> "未知"
            }
        }
    }

    // ==================== 视频能力 ====================

    /**
     * 获取最大帧率
     */
    fun getMaxFrameRate(characteristics: CameraCharacteristics): Int? {
        val ranges = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
        return ranges?.maxOfOrNull { it.upper }
    }

    /**
     * 是否支持高速视频
     */
    fun supportsHighSpeedVideo(characteristics: CameraCharacteristics): Boolean {
        return getAvailableCapabilities(characteristics)
            .contains(CameraCapability.CONSTRAINED_HIGH_SPEED_VIDEO)
    }

    /**
     * 是否支持4K录制
     */
    fun supports4K(characteristics: CameraCharacteristics): Boolean {
        // 简化判断，实际需要检查 StreamConfigurationMap
        val resolution = getPixelArraySize(characteristics)
        return resolution?.contains("3840") == true || resolution?.contains("4096") == true
    }

    /**
     * 是否支持8K录制
     */
    fun supports8K(characteristics: CameraCharacteristics): Boolean {
        val resolution = getPixelArraySize(characteristics)
        return resolution?.contains("7680") == true
    }

    // ==================== 综合信息 ====================

    /**
     * 获取摄像头详细信息
     */
    fun getCameraDetails(cameraId: String): CameraDetails? {
        val characteristics = getCameraCharacteristics(cameraId) ?: return null

        return CameraDetails(
            cameraId = cameraId,
            facing = getCameraFacing(characteristics),
            facingText = getCameraFacingText(characteristics),

            megaPixels = getMegaPixels(characteristics),
            resolution = getPixelArraySize(characteristics),
            sensorSize = getSensorPhysicalSize(characteristics),
            sensorSizeInch = getSensorSizeInch(characteristics),
            pixelSize = getPixelSize(characteristics),
            colorFilterArrangement = getColorFilterArrangement(characteristics),

            focalLength = getFocalLength(characteristics),
            apertures = getAvailableApertures(characteristics),
            fieldOfView = getFieldOfView(characteristics),
            focal35mmEquivalent = getFocal35mmEquivalent(characteristics),
            cropFactor = getCropFactor(characteristics),

            isoRange = getIsoRange(characteristics),
            exposureTimeRange = getExposureTimeRange(characteristics),
            shutterSpeedRange = getShutterSpeedRange(characteristics),
            exposureCompensationRange = getExposureCompensationRange(characteristics),
            exposureCompensationStep = getExposureCompensationStep(characteristics),

            minimumFocusDistance = getMinimumFocusDistance(characteristics),
            minimumFocusDistanceCm = getMinimumFocusDistanceCm(characteristics),
            hyperFocalDistance = getHyperFocalDistance(characteristics),

            hasFlash = hasFlashUnit(characteristics),
            hasOpticalStabilization = hasOpticalStabilization(characteristics),
            hasVideoStabilization = hasVideoStabilization(characteristics),
            hasAutoFocus = hasAutoFocus(characteristics),
            camera2ApiSupport = getCamera2ApiSupport(characteristics),

            maxFaceCount = getMaxFaceCount(characteristics),
            faceDetectionModes = getFaceDetectionModes(characteristics),

            capabilities = getAvailableCapabilities(characteristics),
            supportedFeatures = getSupportedFeatures(characteristics),

            autoExposureModes = getAutoExposureModes(characteristics),
            autoFocusModes = getAutoFocusModes(characteristics),
            whiteBalanceModes = getWhiteBalanceModes(characteristics),
            sceneModes = getSceneModes(characteristics),
            colorEffects = getColorEffects(characteristics),

            maxFrameRate = getMaxFrameRate(characteristics),
            supportsHighSpeedVideo = supportsHighSpeedVideo(characteristics),
            supports4K = supports4K(characteristics),
            supports8K = supports8K(characteristics)
        )
    }

    /**
     * 获取所有摄像头的详细信息列表
     */
    fun getAllCameraDetails(): List<CameraDetails> {
        return cameraIds.mapNotNull { getCameraDetails(it) }
    }
}
