from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel


class ValidationConvertedError(BaseModel):
    type: str
    loc: str
    msg: str


def _loc_to_dot_sep(loc: tuple[str | int, ...]) -> str:
    path = ""
    for i, x in enumerate(loc):
        if isinstance(x, str):
            if i > 0:
                path += "."
            path += x
        elif isinstance(x, int):
            path += f"[{x}]"
        else:
            raise TypeError("Unexpected type")
    return path


def convert_validation_errors(validation_error: RequestValidationError) -> list[ValidationConvertedError]:
    converted: list[ValidationConvertedError] = []
    for error in validation_error.errors():
        converted.append(ValidationConvertedError(
            type=error["type"],
            loc=_loc_to_dot_sep(error["loc"]),
            msg=error["msg"],
        ))
    return converted
