import datetime
import logging
from typing import List

from django.conf import settings

from idm.utils import http

log = logging.getLogger(__name__)


def get_holidays(date_from: datetime.date, offset: int = 21) -> List[datetime.date]:
    try:
        response = http.get(
            str(http.validate_url(settings.CALENDAR_API_HOLIDAYS_URL)),
            params={
                'from': date_from.isoformat(),
                'to': (date_from + datetime.timedelta(days=offset)).isoformat(),
                'for': settings.CALENDAR_API_COUNTRY_CODE,
                'outMode': 'holidays',
            },
            tvm_id=settings.CALENDAR_API_TVM_ID,
        )
        response.raise_for_status()
        result = response.json()
        assert 'error' not in result, result['error']
    except Exception:
        log.warning(f'Error handling calendar api request', exc_info=True)
        return []
    return sorted(datetime.datetime.strptime(holiday['date'], '%Y-%m-%d').date() for holiday in result['holidays'])
