"""Hungarian workday detection with public-holiday lookup and safe fallback."""

from __future__ import annotations

import logging
from datetime import date

import requests

LOGGER = logging.getLogger(__name__)


class HungaryWorkdayCalendar:
    """Decides whether a date is a Hungarian workday for HACCP entries."""

    def __init__(self, timeout_seconds: int = 10) -> None:
        """Initialize an in-memory yearly holiday cache."""

        self.timeout_seconds = timeout_seconds
        self._holidays: dict[int, set[date]] = {}
        self._failed_years: set[int] = set()

    def is_workday(self, day: date) -> bool:
        """Return true for weekdays that are not known Hungarian public holidays."""

        if day.weekday() >= 5:
            return False
        return day not in self.holidays(day.year)

    def holidays(self, year: int) -> set[date]:
        """Fetch Hungarian public holidays from Nager.Date, falling back to none."""

        if year in self._holidays:
            return self._holidays[year]
        if year in self._failed_years:
            return set()

        url = f"https://date.nager.at/api/v3/PublicHolidays/{year}/HU"
        try:
            response = requests.get(url, timeout=self.timeout_seconds)
            response.raise_for_status()
            holidays = {date.fromisoformat(item["date"]) for item in response.json()}
            self._holidays[year] = holidays
            LOGGER.info("Loaded %s Hungarian holidays for %s", len(holidays), year)
            return holidays
        except Exception as exc:  # noqa: BLE001 - fallback keeps generation available.
            self._failed_years.add(year)
            LOGGER.warning(
                "Could not load Hungarian public holidays for %s; using weekends only: %s",
                year,
                exc,
            )
            return set()
