# utils/helpers.py
import json
import time
import uuid
from typing import Dict, Any, List, Optional

def generate_id(prefix: str = "") -> str:
    """生成唯一ID"""
    return f"{prefix}{uuid.uuid4().hex}"

def get_current_timestamp() -> int:
    """获取当前时间戳（毫秒）"""
    return int(time.time() * 1000)

def format_timestamp(timestamp: int, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """格式化时间戳"""
    return time.strftime(format_str, time.localtime(timestamp / 1000))

def parse_json(json_str: str, default=None) -> Any:
    """解析JSON字符串"""
    try:
        return json.loads(json_str)
    except Exception:
        return default

def to_json(obj: Any, pretty: bool = False) -> str:
    """转换为JSON字符串"""
    if pretty:
        return json.dumps(obj, ensure_ascii=False, indent=2)
    else:
        return json.dumps(obj, ensure_ascii=False)

def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
    """合并两个字典"""
    result = dict1.copy()
    result.update(dict2)
    return result

def filter_dict(data: Dict[str, Any], keys: List[str]) -> Dict[str, Any]:
    """过滤字典，只保留指定的键"""
    return {k: v for k, v in data.items() if k in keys}

def exclude_dict(data: Dict[str, Any], keys: List[str]) -> Dict[str, Any]:
    """过滤字典，排除指定的键"""
    return {k: v for k, v in data.items() if k not in keys}