package com.example.m20_gamepad.network.models

/**
 * 错误码 -> 含义映射。依据 proto.md 3.4（异常状态）与第 4 节（通用响应）。
 */
object ErrorCodes {

    /** 返回错误码的人类可读描述；未知码返回 hex 形式。 */
    fun describe(errorCode: Int): String = KNOWN[errorCode] ?: "0x${errorCode.toString(16).uppercase()}"

    private val KNOWN: Map<Int, String> = mapOf(
        // 通用响应错误码（0xE0xx）
        0x0000 to "成功",
        0xE001 to "不支持的数据格式",
        0xE002 to "数据解析失败",
        0xE003 to "不支持的协议类型",
        0xE004 to "缺少必要字段",
        0xE005 to "数据类型不匹配",
        0xE006 to "请求客户端不匹配",
        0xE007 to "无操作权限",
        0xE008 to "状态机不允许",
        0xE009 to "操作失败",
        0xE00A to "不支持的功能",
        0xE00B to "内部错误",

        // 异常状态错误码（0x8xxx）
        0x8001 to "电机温度预警",
        0x8002 to "电机温度过高保护",
        0x8003 to "电机温度致命截止",
        0x8007 to "关节驱动器过温",
        0x8008 to "驱动器欠压保护",
        0x8009 to "驱动器过压保护",
        0x8012 to "与关节驱动器通讯超时",
        0x8016 to "编码器无值",
        0x8020 to "驱动器过流保护",
        0x8022 to "关节角超限",
        0x8027 to "机身姿态错误",
        0x8029 to "运动姿态错误",
        0x8102 to "低电量预警",
        0x8103 to "保护电量",
        0x8107 to "电池放电过温保护",
        0x8115 to "电池充电过温保护",
        0x8117 to "电池单体过压保护",
        0x8201 to "CPU占用率过高预警",
        0x8202 to "CPU温度过高预警",
        0x8211 to "CPU占用率过高保护",
        0x8212 to "CPU温度过高保护",
        0x8501 to "自主充电定位超时",
        0x8503 to "自主充电定位异常",
        0x8506 to "充电桩无电流",
        0x8507 to "充电停障错误",
        0x8510 to "退桩超时"
    )

    /** 关节位编号 -> 名称（component bit 位，自低位起）。 */
    fun jointName(bit: Int): String = when (bit) {
        0 -> "左前 HipX"
        1 -> "左前 HipY"
        2 -> "左前 Knee"
        3 -> "左前 Wheel"
        4 -> "右前 HipX"
        5 -> "右前 HipY"
        6 -> "右前 Knee"
        7 -> "右前 Wheel"
        8 -> "左后 HipX"
        9 -> "左后 HipY"
        10 -> "左后 Knee"
        11 -> "左后 Wheel"
        12 -> "右后 HipX"
        13 -> "右后 HipY"
        14 -> "右后 Knee"
        15 -> "右后 Wheel"
        else -> "未知部件($bit)"
    }

    /** 解析 component 位掩码为部件名称列表。 */
    fun componentNames(component: Int): List<String> {
        if (component == 0) return emptyList()
        val result = mutableListOf<String>()
        for (bit in 0 until 16) {
            if ((component shr bit) and 1 == 1) {
                result.add(jointName(bit))
            }
        }
        // bit0/1 在电池上下文表示电池，但关节上下文优先按关节解释
        return result
    }
}
