from textwrap import shorten
from typing import Any, Optional

from ldnode.calculator.handlers.models import T, TaskResponse


def response(
    data_type: str, data: T, storage_key: Optional[str] = None
) -> TaskResponse[T]:
    """正常响应"""
    answer: TaskResponse[T] = {
        "data_type": data_type,
        "data": data,
    }
    if storage_key:
        answer["storage_key"] = storage_key
    return answer


def error_response(error_msg: Any) -> TaskResponse[str]:
    """错误响应"""
    return {
        "data_type": "error",
        "data": shorten(f"{error_msg}", width=255, placeholder="..."),
    }
