import hashlib
import hmac
import json
from typing import Dict, Any

class SignatureGenerator:
    """签名生成器"""

    def __init__(self, sign_key: str):
        self.sign_key = sign_key

    def hmac_sha256(self, message: str) -> str:
        """使用HMAC-SHA256算法生成签名"""
        key_bytes = self.sign_key.encode('utf-8')
        message_bytes = message.encode('utf-8')
        return hmac.new(key_bytes, message_bytes, hashlib.sha256).hexdigest()

    def generate_signature(self, url_path: str, data: Dict[str, Any] = None) -> str:
        """生成请求签名"""
        sign_message = url_path

        if data:
            # 将布尔值转换为字符串
            data_copy = data.copy()
            for key, value in data_copy.items():
                if isinstance(value, bool):
                    data_copy[key] = "true" if value else "false"

            # 添加请求体到签名消息
            sign_message += json.dumps(data_copy, ensure_ascii=False, separators=(',', ':'))

        return self.hmac_sha256(sign_message)
