import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

from django.conf import settings


CALENDARIFIC_URL = (
    "https://calendarific.com/api/v2/holidays"
)


def get_indian_holidays(
    year,
    location=None
):
    """
    Automatically fetch India holidays.

    No:
        holidays package
        python-dateutil
        requests

    Uses Python standard library urllib.
    """

    api_key = getattr(
        settings,
        "CALENDARIFIC_API_KEY",
        ""
    )

    if not api_key:

        raise Exception(
            "CALENDARIFIC_API_KEY is not configured."
        )

    # ---------------------------------------------------------
    # API PARAMETERS
    # ---------------------------------------------------------

    params = {
        "api_key": api_key,
        "country": "IN",
        "year": year,

        # National + local + religious holidays
        "type": "national,local,religious",
    }

    # Optional state/region
    if location:

        params["location"] = location

    query_string = urlencode(params)

    url = (
        f"{CALENDARIFIC_URL}"
        f"?{query_string}"
    )

    request = Request(
        url,
        headers={
            "User-Agent": (
                "HRNexus-Holiday-API/1.0"
            ),
            "Accept": "application/json",
        },
        method="GET",
    )

    # ---------------------------------------------------------
    # CALL CALENDAR API
    # ---------------------------------------------------------

    try:

        with urlopen(
            request,
            timeout=20
        ) as response:

            status_code = response.status

            response_body = (
                response.read()
                .decode("utf-8")
            )

    except HTTPError as error:

        try:
            error_body = (
                error.read()
                .decode("utf-8")
            )
        except Exception:
            error_body = ""

        raise Exception(
            "Calendar API error "
            f"HTTP {error.code}: "
            f"{error_body}"
        )

    except URLError as error:

        raise Exception(
            "Unable to connect to "
            "holiday calendar service: "
            f"{error.reason}"
        )

    except Exception as error:

        raise Exception(
            "Holiday calendar request failed: "
            f"{error}"
        )

    # ---------------------------------------------------------
    # CHECK RESPONSE
    # ---------------------------------------------------------

    if status_code != 200:

        raise Exception(
            "Holiday API returned HTTP "
            f"{status_code}"
        )

    if not response_body.strip():

        raise Exception(
            "Holiday API returned an empty response."
        )

    # ---------------------------------------------------------
    # PARSE JSON
    # ---------------------------------------------------------

    try:

        data = json.loads(
            response_body
        )

    except json.JSONDecodeError:

        raise Exception(
            "Holiday API returned invalid JSON."
        )

    # ---------------------------------------------------------
    # CHECK API RESPONSE
    # ---------------------------------------------------------

    response_data = data.get(
        "response",
        {}
    )

    holidays = response_data.get(
        "holidays",
        []
    )

    if not isinstance(
        holidays,
        list
    ):

        raise Exception(
            "Invalid holiday data received."
        )

    # ---------------------------------------------------------
    # CONVERT TO HRNEXUS FORMAT
    # ---------------------------------------------------------

    result = []

    seen = set()

    for holiday in holidays:

        holiday_name = (
            holiday.get("name")
        )

        holiday_date = (
            holiday.get("date", {})
            .get("iso")
        )

        description = (
            holiday.get("description")
            or f"Automatically imported "
               f"for {year}."
        )

        if not holiday_name:
            continue

        if not holiday_date:
            continue

        # Prevent duplicate holiday records
        duplicate_key = (
            holiday_date,
            holiday_name
        )

        if duplicate_key in seen:
            continue

        seen.add(
            duplicate_key
        )

        # -----------------------------------------------------
        # DETERMINE TYPE
        # -----------------------------------------------------

        holiday_types = holiday.get(
            "type",
            []
        )

        holiday_type = "National"

        if holiday_types:

            type_text = " ".join(
                str(value).lower()
                for value in holiday_types
            )

            if "local" in type_text:

                holiday_type = "Regional"

            elif "religious" in type_text:

                holiday_type = "Optional"

            elif "national" in type_text:

                holiday_type = "National"

        result.append(
            {
                "date": holiday_date,

                "name": holiday_name,

                "holiday_type":
                    holiday_type,

                "description":
                    description,
            }
        )

    # ---------------------------------------------------------
    # SORT BY DATE
    # ---------------------------------------------------------

    result.sort(
        key=lambda item: item["date"]
    )

    return result