import logging
from typing import Dict

import urllib3
from django.conf import settings
from lxml import etree

from idm.utils import http

log = logging.getLogger(__name__)


def get_conductor_groups() -> Dict[int, str]:
    max_retries = urllib3.Retry(
        total=settings.IDM_CONDUCTOR_RETRIES_COUNT,
        backoff_factor=settings.IDM_CONDUCTOR_BACKOFF_FACTOR,
        status_forcelist=settings.IDM_CONDUCTOR_STATUS_FORCELIST,
    )
    response = http.get(
        http.validate_url(settings.IDM_CONDUCTOR_GROUPS_URL),
        oauth_token=settings.IDM_STAFF_OAUTH_TOKEN,
        timeout=settings.IDM_CONDUCTOR_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:
        xml = etree.fromstring(response.content)
        conductor_groups = {}
        for item in xml.getchildren():
            item_dict = {x.tag: x.text for x in item.getchildren()}
            conductor_groups[int(item_dict['id'])] = item_dict['name']
    except Exception:
        log.exception('Could not parse response from Conductor')
        raise

    return conductor_groups
