from typing import Optional

from smb.common.http_client import BaseHttpClientException, collect_errors

from smb.common.aiotvm import HttpClientWithTvm


class BlackboxClientException(BaseHttpClientException):
    pass


class BlackboxClient(HttpClientWithTvm):
    _session_host: str

    def __init__(self, *args, session_host: str, **kwargs):
        super().__init__(*args, **kwargs)
        self._session_host = session_host

    @collect_errors
    async def sessionid(
        self,
        user_ip: str,
        session_id: str,
        ssl_session_id: Optional[str] = None,
        **extra_params,
    ):
        """
        Calls sessionid method of blackbox.
        https://docs.yandex-team.ru/blackbox/methods/sessionid

        Validates session cookies and returns requested user data, raises on
        authorization failure.
        """
        params = {
            "method": "sessionid",
            "userip": user_ip,
            "host": self._session_host,
            "sessionid": session_id,
            "format": "json",
            **extra_params,
        }
        if ssl_session_id is not None:
            params["sslsessionid"] = ssl_session_id

        response = await self.request(
            method="GET",
            uri="/blackbox",
            params=params,
            expected_statuses=[200],
            metric_name="sessionid",
        )

        if response["status"]["value"] not in ["VALID", "NEED_RESET"]:
            raise BlackboxClientException(
                "Bad status {}".format(response["status"]["value"])
            )

        return response
