package com.xyzshell.andinfo.libs

import android.content.Context
import android.media.MediaDrm
import android.os.Build
import java.util.UUID

/**
 * DRM（数字版权管理）信息工具类
 * 提供设备支持的DRM方案信息，包括Widevine、PlayReady等
 */
class DRMInfo(private val context: Context) {

    /**
     * DRM详细信息数据类
     */
    data class DRMDetail(
        val uuid: String,                      // DRM方案的UUID
        val name: String,                      // DRM方案名称
        val vendor: String?,                   // 供应商
        val version: String?,                  // 版本号
        val description: String?,              // 描述信息
        val algorithms: List<String>?,         // 支持的加密算法列表
        val deviceUniqueId: String?,           // 设备唯一ID（十六进制）
        val securityLevel: String?,            // 安全级别（如L1、L3等）
        val systemId: String?,                 // 系统ID
        val openSessionCount: Int?,            // 当前打开的会话数（Android 9及以上）
        val maxSessionCount: Int?,             // 最大会话数（Android 9及以上）
        val connectedHdcpLevel: Int?,          // 当前连接的HDCP级别（Android 9及以上）
        val maxHdcpLevel: Int?,                // 最高支持的HDCP级别（Android 9及以上）
    )

    /**
     * 获取所有支持的DRM方案列表
     * @return DRM UUID列表
     */
    fun getSupportedDrmSchemes(): List<UUID> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上使用官方API
            MediaDrm.getSupportedCryptoSchemes().toList()
        } else {
            // Android 11以下遍历已知的DRM方案
            CONTENT_PROTECTION_SCHEMES.keys.filter { uuid ->
                try {
                    val mediaDrm = MediaDrm(uuid)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        mediaDrm.close()
                    } else {
                        @Suppress("DEPRECATION")
                        mediaDrm.release()
                    }
                    true
                } catch (e: Exception) {
                    false
                }
            }
        }
    }

    /**
     * 获取指定UUID的DRM详细信息
     * @param uuid DRM方案的UUID
     * @return DRM详细信息，如果不支持则返回null
     */
    fun getDrmDetail(uuid: UUID): DRMDetail? {
        val mediaDrm = try {
            MediaDrm(uuid)
        } catch (e: Exception) {
            return null
        }

        return try {
            val name = CONTENT_PROTECTION_SCHEMES[uuid] ?: "Unknown DRM Scheme"

            DRMDetail(
                uuid = uuid.toString(),
                name = name,
                vendor = getPropertyStringSafe(mediaDrm, MediaDrm.PROPERTY_VENDOR),
                version = getPropertyStringSafe(mediaDrm, MediaDrm.PROPERTY_VERSION),
                description = getPropertyStringSafe(mediaDrm, MediaDrm.PROPERTY_DESCRIPTION),
                algorithms = getPropertyStringSafe(mediaDrm, MediaDrm.PROPERTY_ALGORITHMS)
                    ?.split(",")
                    ?.filter { it.isNotEmpty() },
                deviceUniqueId = getPropertyByteArraySafe(mediaDrm, MediaDrm.PROPERTY_DEVICE_UNIQUE_ID)
                    ?.toHexString(),
                securityLevel = getPropertyStringSafe(mediaDrm, "securityLevel"),
                systemId = getPropertyStringSafe(mediaDrm, "systemId"),
                openSessionCount = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    try {
                        mediaDrm.openSessionCount
                    } catch (e: Exception) {
                        null
                    }
                } else null,
                maxSessionCount = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    try {
                        mediaDrm.maxSessionCount
                    } catch (e: Exception) {
                        null
                    }
                } else null,
                connectedHdcpLevel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    try {
                        mediaDrm.connectedHdcpLevel
                    } catch (e: Exception) {
                        null
                    }
                } else null,
                maxHdcpLevel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    try {
                        mediaDrm.maxHdcpLevel
                    } catch (e: Exception) {
                        null
                    }
                } else null,
            )
        } finally {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                mediaDrm.close()
            } else {
                @Suppress("DEPRECATION")
                mediaDrm.release()
            }
        }
    }

    /**
     * 获取所有支持的DRM方案的详细信息
     * @return DRM详细信息列表
     */
    fun getAllDrmDetails(): List<DRMDetail> {
        return getSupportedDrmSchemes().mapNotNull { uuid ->
            getDrmDetail(uuid)
        }
    }

    /**
     * 安全地获取MediaDrm字符串属性
     */
    private fun getPropertyStringSafe(mediaDrm: MediaDrm, property: String): String? {
        return try {
            mediaDrm.getPropertyString(property)
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 安全地获取MediaDrm字节数组属性
     */
    private fun getPropertyByteArraySafe(mediaDrm: MediaDrm, property: String): ByteArray? {
        return try {
            mediaDrm.getPropertyByteArray(property)
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 字节数组转十六进制字符串
     */
    private fun ByteArray.toHexString(): String {
        return joinToString("") { "%02x".format(it) }
    }

    /**
     * 根据HDCP级别获取描述
     */
    fun getHdcpLevelDescription(level: Int): String {
        return HDCP_LEVEL_NAMES[level] ?: "Unknown ($level)"
    }

    companion object {
        /**
         * 已知的内容保护方案UUID和名称映射
         * 来源: DASH-IF (https://dashif.org/identifiers/content_protection/)
         */
        val CONTENT_PROTECTION_SCHEMES = mapOf(
            UUID.fromString("6dd8b3c3-45f4-4a68-bf3a-64168d01a4a6") to "ABV DRM (MoDRM)",
            UUID.fromString("f239e769-efa3-4850-9c16-a903c6932efb") to "Adobe Primetime DRM v4",
            UUID.fromString("616c7469-6361-7374-2d50-726f74656374") to "Alticast",
            UUID.fromString("94ce86fb-07ff-4f43-adb8-93d2fa968ca2") to "Apple FairPlay",
            UUID.fromString("29701fe4-3cc7-4a34-8c5b-ae90c7439a47") to "Apple FairPlay (非官方)",
            UUID.fromString("279fe473-512c-48fe-ade8-d176fee6b40f") to "Arris Titanium",
            UUID.fromString("3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c") to "ChinaDRM",
            UUID.fromString("3ea8778f-7742-4bf9-b18b-e834b2acbd47") to "ClearKey AES-128",
            UUID.fromString("be58615b-19c4-4684-88b3-c8c57e99e957") to "ClearKey SAMPLE-AES",
            UUID.fromString("e2719d58-a985-b3c9-781a-b030af78d30e") to "ClearKey DASH-IF",
            UUID.fromString("644fe7b5-260f-4fad-949a-0762ffb054B4") to "CMLA (OMA DRM)",
            UUID.fromString("37c33258-7b99-4c7e-b15d-19af74482154") to "Commscope Titanium V3",
            UUID.fromString("45d481cb-8fe0-49c0-ada9-ab2d2455b2f2") to "CoreCrypt",
            UUID.fromString("dcf4e3e3-62f1-5818-7ba6-0a6fe33ff3dd") to "DigiCAP SmartXess",
            UUID.fromString("35bf197b-530e-42d7-8b65-1b4bf415070f") to "DivX DRM Series 5",
            UUID.fromString("80a6be7e-1448-4c37-9e70-d5aebe04c8d2") to "Irdeto Content Protection",
            UUID.fromString("5e629af5-38da-4063-8977-97ffbd9902d4") to "Marlin Adaptive Streaming Simple Profile V1.0",
            UUID.fromString("9a04f079-9840-4286-ab92-e65be0885f95") to "Microsoft PlayReady",
            UUID.fromString("6a99532d-869f-5922-9a91-113ab7b1e2f3") to "MobiTV DRM",
            UUID.fromString("adb41c24-2dbf-4a6d-958b-4457c0d27b95") to "Nagra MediaAccess PRM 3.0",
            UUID.fromString("1f83e1e8-6ee9-4f0d-ba2f-5ec4e3ed1a66") to "SecureMedia",
            UUID.fromString("992c46e6-c437-4899-b6a0-50fa91ad0e39") to "SecureMedia SteelKnot",
            UUID.fromString("a68129d3-575b-4f1a-9cba-3223846cf7c3") to "Synamedia/Cisco/NDS VideoGuard DRM",
            UUID.fromString("aa11967f-cc01-4a4a-8e99-c5d3dddfea2d") to "Unitend DRM (UDRM)",
            UUID.fromString("9a27dd82-fde2-4725-8cbc-4234aa06ec09") to "Verimatrix VCAS",
            UUID.fromString("b4413586-c58c-ffb0-94a5-d4896c1af6c3") to "Viaccess-Orca DRM (VODRM)",
            UUID.fromString("793b7956-9f94-4946-a942-23e7ef7e44b4") to "VisionCrypt",
            UUID.fromString("1077efec-c0b2-4d02-ace3-3c1e52e2fb4b") to "W3C Common PSSH box",
            UUID.fromString("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed") to "Widevine Content Protection",
        )

        /**
         * HDCP级别名称映射
         * HDCP (High-bandwidth Digital Content Protection) 高带宽数字内容保护
         */
        val HDCP_LEVEL_NAMES = mapOf(
            0 to "HDCP_NONE (无)",
            1 to "HDCP_V1 (1.x)",
            2 to "HDCP_V2 (2.0)",
            3 to "HDCP_V2_1 (2.1)",
            4 to "HDCP_V2_2 (2.2)",
            5 to "HDCP_V2_3 (2.3)",
            255 to "HDCP_NO_DIGITAL_OUTPUT (无数字输出)",
        )

        /**
         * 常用的DRM UUID常量
         */
        val WIDEVINE_UUID = UUID.fromString("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed")
        val PLAYREADY_UUID = UUID.fromString("9a04f079-9840-4286-ab92-e65be0885f95")
        val CLEARKEY_UUID = UUID.fromString("e2719d58-a985-b3c9-781a-b030af78d30e")
    }
}