import zoneinfo

from django.utils import timezone


class TimezoneMiddleware:
    """Activate the user's local timezone from the ``user_tz`` cookie.

    The cookie is set client-side via ``Intl.DateTimeFormat().resolvedOptions().timeZone``
    on every page load, so it reflects the browser's OS timezone rather than
    the server's configured TIME_ZONE.  Invalid or absent cookies fall back to
    Django's default (UTC).
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        tz_name = request.COOKIES.get("user_tz")
        if tz_name:
            try:
                timezone.activate(zoneinfo.ZoneInfo(tz_name))
            except (zoneinfo.ZoneInfoNotFoundError, KeyError):
                timezone.deactivate()
        else:
            timezone.deactivate()
        response = self.get_response(request)
        timezone.deactivate()
        return response
