"""
响应工具函数

提供标准化响应创建和元数据注入功能
"""
from datetime import datetime
from typing import Any, Optional
from fastapi import Request
from src.models.response import ResponseModel, ErrorCode


def create_response(
    data: Any = None,
    message: str = "success",
    code: str | ErrorCode = ErrorCode.SUCCESS,
    request: Optional[Request] = None
) -> ResponseModel:
    """创建标准化响应

    自动添加 request_id 和 timestamp 到 metadata

    Args:
        data: 响应数据
        message: 响应消息
        code: 响应代码 (ErrorCode.SUCCESS 表示成功)
        request: FastAPI Request 对象 (用于获取 request_id)

    Returns:
        ResponseModel: 标准化响应对象
    """
    metadata = {
        "timestamp": datetime.now().isoformat()
    }

    # 如果有 request 对象,添加 request_id
    if request and hasattr(request.state, "request_id"):
        metadata["request_id"] = request.state.request_id

    return ResponseModel(
        code=code,
        message=message,
        data=data,
        meta=metadata
    )


def success_response(
    data: Any = None,
    message: str = "success",
    request: Optional[Request] = None
) -> ResponseModel:
    """创建成功响应

    Args:
        data: 响应数据
        message: 响应消息
        request: FastAPI Request 对象

    Returns:
        ResponseModel: 成功响应
    """
    return create_response(data=data, message=message, code=ErrorCode.SUCCESS, request=request)


def error_response(
    code: ErrorCode,
    message: str,
    data: Any = None,
    request: Optional[Request] = None
) -> ResponseModel:
    """创建错误响应

    Args:
        code: 错误代码 (ErrorCode 枚举)
        message: 错误消息
        data: 错误详情数据
        request: FastAPI Request 对象

    Returns:
        ResponseModel: 错误响应
    """
    return create_response(data=data, message=message, code=code, request=request)


def add_metadata(response: ResponseModel, request: Optional[Request] = None) -> ResponseModel:
    """为已有响应添加元数据

    Args:
        response: 已有的响应对象
        request: FastAPI Request 对象

    Returns:
        ResponseModel: 添加了元数据的响应对象
    """
    if response.meta is None:
        from src.models.response import ResponseMeta
        response.meta = ResponseMeta()

    # 添加 timestamp
    if not hasattr(response.meta, "timestamp") or response.meta.timestamp is None:
        response.meta.timestamp = datetime.now().isoformat()

    # 添加 request_id
    if request and hasattr(request.state, "request_id"):
        if not hasattr(response.meta, "request_id") or response.meta.request_id is None:
            response.meta.request_id = request.state.request_id

    return response
