#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from abc import ABC
from typing import Any, Dict, Generic, List, Optional, TypeVar

from pydantic import BaseModel, ValidationError
from requests import Response
from typing_extensions import Self

from pendingai.exceptions import InternalServerErrorException
from pendingai.utils.logger import Logger

logger = Logger().get_logger()


class ResponseModel(BaseModel, ABC):
    """
    HTTP Response model provides a convenient method to parse API responses into a
    structured datamodel. It can be built using an HTTP response object and will
    attempt to parse the JSON content into the model.
    """

    @classmethod
    def from_response(cls, response: Response) -> Self:
        try:
            return cls.model_validate(response.json())
        except ValidationError as e:
            logger.error(f"Failed to parse response: {e}", exc_info=True)
            raise InternalServerErrorException("Unexpected response data") from e


class ApiResource(ResponseModel):
    id: str
    object: str


T = TypeVar("T", bound=ApiResource)


class ApiResourceList(ResponseModel, Generic[T]):
    object: str
    data: List[T]
    metadata: Optional[Dict[str, Any]] = None
    links: Optional[Dict[str, Any]] = None
