"""
SKU键生成工具
用于生成统一的SKU标识符
"""

import hashlib
from typing import Optional


def generate_sku_key(product_name: str, sales_attributes: Optional[str] = None) -> str:
    """
    生成SKU键
    
    Args:
        product_name: 产品名称
        sales_attributes: 销售属性
    
    Returns:
        SKU键字符串
    """
    if not product_name:
        return ""
    
    # 清理输入
    product_name = str(product_name).strip()
    sales_attributes = str(sales_attributes).strip() if sales_attributes else ""
    
    # 组合键值
    key_parts = [product_name]
    if sales_attributes:
        key_parts.append(sales_attributes)
    
    # 生成键值
    combined_key = "|".join(key_parts)
    
    # 生成哈希作为SKU键
    sku_hash = hashlib.md5(combined_key.encode('utf-8')).hexdigest()[:16]
    
    return f"{sku_hash}_{len(key_parts)}"


def validate_sku_key(sku_key: str) -> bool:
    """
    验证SKU键格式是否正确
    
    Args:
        sku_key: SKU键
    
    Returns:
        是否有效
    """
    if not sku_key or not isinstance(sku_key, str):
        return False
    
    parts = sku_key.split('_')
    if len(parts) != 2:
        return False
    
    hash_part, count_part = parts
    
    # 验证哈希部分长度
    if len(hash_part) != 16:
        return False
    
    # 验证计数部分
    try:
        count = int(count_part)
        return count > 0
    except ValueError:
        return False