import logging
import requests

from requests.exceptions import ConnectionError, Timeout

from django.conf import settings

from intranet.femida.src.core.exceptions import FemidaError


logger = logging.getLogger(__name__)


class VanadiumError(FemidaError):
    pass


class VanadiumAPI:
    # https://wiki.yandex-team.ru/vanadium/http-api/

    @classmethod
    def _request(cls, method, url, params=None, data=None):
        try:
            response = requests.request(
                method=method,
                url=f'https://{settings.VANADIUM_HOST}/{url}',
                params=params,
                json=data,
                timeout=30,
            )
        except (ConnectionError, Timeout):
            raise VanadiumError('Vanadium is not responding')

        if not response.ok:
            logger.error(
                'Vanadium error %s, response: %s',
                response.status_code,
                response.content.decode('utf-8'),
            )
            raise VanadiumError('Wrong status code from Vanadium')

        try:
            data = response.json() if response.content else {}
        except ValueError:
            logger.exception(
                'Error during parse Vanadium response: %s',
                response.content.decode('utf-8'),
            )
            raise VanadiumError('Error during parse Vanadium response')

        return data

    @classmethod
    def enqueue_batch(cls, table_path):
        data = {
            'yt-cluster': 'hahn',
            'user': 'robot-femida',
            'input-table': table_path,
            'batch-name-prefix': 'femida',
        }
        return cls._request('POST', 'api/batch/enqueue', data=data)

    @classmethod
    def check_batch_status(cls, yt_cluster, queue_name, batch_name):
        data = {
            'yt-cluster': yt_cluster,
            'queue-name': queue_name,
            'batch-table-name': batch_name,
        }
        return cls._request('POST', 'api/batch/status', data=data)

    @classmethod
    def batch_info(cls, uuid):
        return cls._request('GET', f'api/batch/{uuid}')
