"""
API响应工具模块
用于处理API响应数据的转换和统一响应格式
"""
from typing import Dict, Any, List, Optional
from datetime import datetime

class ApiResponseUtil:
    """API响应工具类"""


def success_response(data: Any = None, message: str = "操作成功", code: int = 200) -> Dict[str, Any]:
    """
    创建成功响应

    Args:
        data: 响应数据
        message: 响应消息
        code: HTTP状态码

    Returns:
        统一格式的成功响应
    """
    response = {
        "success": True,
        "code": code,
        "message": message,
        "timestamp": datetime.now().isoformat()
    }

    if data is not None:
        response["data"] = data

    return response


def error_response(message: str = "操作失败", error: str = None, code: int = 400) -> Dict[str, Any]:
    """
    创建错误响应

    Args:
        message: 错误消息
        error: 详细错误信息
        code: HTTP状态码

    Returns:
        统一格式的错误响应
    """
    response = {
        "success": False,
        "code": code,
        "message": message,
        "timestamp": datetime.now().isoformat()
    }

    if error:
        response["error"] = error

    return response


def paginated_response(data: List[Any], total: int, page: int = 1,
                      page_size: int = 10, message: str = "查询成功") -> Dict[str, Any]:
    """
    创建分页响应

    Args:
        data: 分页数据
        total: 总数据量
        page: 当前页码
        page_size: 每页大小
        message: 响应消息

    Returns:
        统一格式的分页响应
    """
    total_pages = (total + page_size - 1) // page_size

    return success_response(
        data={
            "list": data,
            "pagination": {
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "has_next": page < total_pages,
                "has_prev": page > 1
            }
        },
        message=message
    )