from __future__ import annotations

from typing import Any, Dict

try:
    from django.contrib.sites.models import Site
except Exception:  # pragma: no cover - sites may be disabled in some envs
    Site = None  # type: ignore


def current_site(request) -> Dict[str, Any]:
    """Inject the current Site object as `current_site` into templates.

    Falls back to None if Sites is not available.
    """
    site = None
    # Prefer host-based resolution so different domains work even when SITE_ID is set.
    if Site is not None:
        try:
            host = request.get_host().split(":")[0].lower()
            site = Site.objects.get(domain__iexact=host)
        except Exception:
            try:
                # Fallback to the default configured Site
                site = Site.objects.get_current()
            except Exception:
                site = None
    return {"current_site": site}
