from pydantic import BaseModel, Field, field_validator
from typing import Generic, TypeVar, Optional

from huibiao_framework.backend import CommonStatusCode
from huibiao_framework.backend.error_code_manage import ApiErrorCodeManage
from huibiao_framework.backend.status_code import BasicStatusCode

T = TypeVar("T")


class BaseRespVo(BaseModel, Generic[T]):
    code: int
    message: str
    result: Optional[T] = Field(None, description="结果")
    requestId: Optional[str] = None

    @classmethod
    def success(cls, result: Optional[T]):
        return cls(
            code=CommonStatusCode.SUCCESS.code,
            result=result,
            message=CommonStatusCode.SUCCESS.msg,
        )

    @classmethod
    def from_status_code(cls, http_status: BasicStatusCode, **kwargs):
        return cls(
            code=http_status.code,
            message=http_status.msg.format(**kwargs),
            result=None,
        )

    def set_request_id(self, request_id: Optional[str]) -> "BaseRespVo":
        self.requestId = request_id
        return self

    @field_validator("code", mode="after")
    @classmethod
    def validate_code_prefix(cls, v: int):
        """
        对于失败的状态码，添加服务号码前缀
        """
        if v < 0:
            raise ValueError("code 必须是非负数")

        v = ApiErrorCodeManage.add_service_prefix(v)

        return v
