import json
import logging
import requests
import waffle

from constance import config
from django.conf import settings

from intranet.femida.src.isearch.exceptions import ISearchError
from intranet.femida.src.utils.tvm2_client import get_service_ticket

logger = logging.getLogger(__name__)


def make_api_request(params, user_ticket, ip):
    url = settings.ISEARCH_API_URL
    try:
        response = requests.get(
            url=url,
            params=params,
            headers={
                'X-Forwarded-For': ip,
                'X-Ya-User-Ticket': user_ticket,
                'X-Ya-Service-Ticket': get_service_ticket(settings.TVM_ISEARCH_CLIENT_ID),
            },
            verify=settings.YANDEX_INTERNAL_CERT_PATH,
            timeout=config.ISEARCH_TIMEOUT,
        )
    except (requests.ConnectionError, requests.Timeout):
        logging.exception('ISearch api is not responding')
        raise ISearchError

    if response.status_code != 200:
        logger.error('ISearch api responded with status code %s', response.status_code)
        raise ISearchError

    return response


def make_push_request(url, data, safe=False):
    if waffle.switch_is_active('disable_push_to_isearch'):
        return
    headers = {
        'X-Ya-Service-Ticket': get_service_ticket(settings.TVM_ISEARCH_CLIENT_ID),
        'Content-Type': 'application/json',
        'Accept': 'text/plain',
    }
    try:
        response = requests.post(
            url=url,
            data=json.dumps(data),
            headers=headers,
            verify=settings.YANDEX_INTERNAL_CERT_PATH,
            timeout=config.ISEARCH_TIMEOUT,
        )
    except (requests.ConnectionError, requests.Timeout):
        logging.exception('ISearch push is not responding')
        if not safe:
            raise
        return {}

    if response.status_code != 200:
        logger.error(
            'ISearch push responded with status code %s', response.status_code,
        )
        if not safe:
            response.raise_for_status()
