# -*- coding: utf-8 -*-
import logging
from typing import Dict, Any

import urllib3
from django.conf import settings

from idm.utils import http

log = logging.getLogger(__name__)


def get_macros() -> Dict[str, Any]:
    max_retries = urllib3.Retry(
        total=settings.IDM_RACKTABLES_RETRIES_COUNT,
        backoff_factor=settings.IDM_RACKTABLES_BACKOFF_FACTOR,
        status_forcelist=settings.IDM_RACKTABLES_STATUS_FORCELIST,
    )
    response = http.get(
        http.validate_url(settings.RACKTABLES_MACROS_URL),
        oauth_token=settings.IDM_STAFF_OAUTH_TOKEN,
        timeout=settings.IDM_RACKTABLES_TIMEOUT,
        max_retries=max_retries,
        use_client_certificate=False,
    )
    if response.status_code != 200:
        log.error('Wrong status: %s. Content (first 1000 symbols): %s', response.status_code, response.content[:1000])
        response.raise_for_status()

    try:
        return response.json()
    except Exception:
        log.exception('Could not parse response. Content (first 1000 symbols): %s', response.content[:1000])
        raise
