"""设备 ID 衍生字段（MD5 等），供 API 与控制台展示。"""

from __future__ import annotations

import hashlib
from typing import Any


def device_id_md5(device_id: str) -> str:
    """设备 serial / device_id 的 MD5（小写 hex，32 位）。"""
    raw = (device_id or "").strip()
    return hashlib.md5(raw.encode("utf-8")).hexdigest()


def enrich_device_id_fields(device: dict) -> dict:
    """为设备 dict 补充 device_id_md5（不改变原 dict 引用时可就地更新）。"""
    did = device.get("device_id") or device.get("serial") or ""
    if did:
        device["device_id_md5"] = device_id_md5(str(did))
    return device


def sanitize_sensitive_fields(value: Any) -> Any:
    """递归移除设备资料中的配对密钥，并对连接 URL 去除查询参数。"""
    if isinstance(value, dict):
        result = {}
        for key, item in value.items():
            if key == "pairing_token":
                continue
            if key == "server_url" and isinstance(item, str):
                result[key] = item.split("?", 1)[0]
            else:
                result[key] = sanitize_sensitive_fields(item)
        return result
    if isinstance(value, list):
        return [sanitize_sensitive_fields(item) for item in value]
    return value
