"""Provide cached access to the current player count of the Eve server."""

from typing import Optional

from django.core.cache import cache
from esi.exceptions import HTTPError

from allianceauth.services.hooks import get_extension_logger

from memberaudit.providers import esi

logger = get_extension_logger(__name__)

_CACHE_KEY = "memberaudit-player-count"
_TIMEOUT = 1 * 60


def get() -> Optional[int]:
    """Return cached player count from ESI or None if offline."""
    return cache.get_or_set(
        key=_CACHE_KEY, default=_fetch_player_count, timeout=_TIMEOUT
    )


def clear_cache():
    """Clear cache."""
    cache.delete(_CACHE_KEY)


def _fetch_player_count() -> Optional[int]:
    try:
        status = esi.client.Status.GetStatus().result(use_etag=False)
    except HTTPError:
        return None

    return status.players
