from __future__ import annotations

import logging
from requests import Response
from requests.models import RequestsJSONDecodeError
from typing import Any, List, NamedTuple, Optional


class SyncResult(NamedTuple):
    success: bool
    status_code: int
    data: Any

    @staticmethod
    def from_requests_response(
        response: Optional[Response], pass_status_codes: List[int] = (200,)
    ) -> SyncResult:
        """Create SyncResult from requests response.

        :param Optional[Response] response: The response
        :param List[int]: pass_status_codes: List of status codes representing success
        :return: Object containing sync results
        :rtype: SyncResult
        """
        if response is None:
            return SyncResult(False, None, None)

        try:
            response_json = response.json()
        except RequestsJSONDecodeError as e:
            logging.warning("Failed to decode server JSON response: %s", e)
            return SyncResult(False, None, None)

        success = response.status_code in pass_status_codes

        return SyncResult(success, response.status_code, response_json)
