import logging
import re
from urllib.parse import urlparse

from django.conf import settings
from django.utils.cache import add_never_cache_headers
from django.utils.cache import patch_cache_control
from django.utils.cache import patch_response_headers

logger = logging.getLogger(__name__)

STAC_BASE = settings.STAC_BASE
STAC_BASE_V = settings.STAC_BASE_V


class CacheHeadersMiddleware:
    '''Middleware that adds appropriate cache headers to GET and HEAD methods.

    NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints are marked as never cache.
    '''

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

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        # match /xxx or /api/stac/xxx
        # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token
        if re.match(fr'^(/{STAC_BASE})?/\w+$', request.path):
            add_never_cache_headers(response)
        elif (
            request.method in ('GET', 'HEAD') and
            not request.path.startswith(urlparse(settings.STATIC_URL).path)
        ):
            logger.debug(
                "Patching cache headers for request %s %s",
                request.method,
                request.path,
                extra={"request": request}
            )
            patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS)
            patch_cache_control(response, public=True)

        return response

[((10, 9, 10, 36), 'logging.getLogger', 'logging.getLogger', ({(10, 27, 10, 35): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((35, 11, 35, 60), 're.match', 're.match', ({(35, 20, 35, 45): 'f"""^(/{STAC_BASE})?/\\\\w+$"""', (35, 47, 35, 59): 'request.path'}, {}), "(f'^(/{STAC_BASE})?/\\\\w+$', request.path)", False, 'import re\n'), ((36, 12, 36, 45), 'django.utils.cache.add_never_cache_headers', 'add_never_cache_headers', ({(36, 36, 36, 44): 'response'}, {}), '(response)', False, 'from django.utils.cache import add_never_cache_headers\n'), ((47, 12, 47, 79), 'django.utils.cache.patch_response_headers', 'patch_response_headers', ({(47, 35, 47, 43): 'response', (47, 45, 47, 78): 'settings.CACHE_MIDDLEWARE_SECONDS'}, {}), '(response, settings.CACHE_MIDDLEWARE_SECONDS)', False, 'from django.utils.cache import patch_response_headers\n'), ((48, 12, 48, 54), 'django.utils.cache.patch_cache_control', 'patch_cache_control', (), '', False, 'from django.utils.cache import patch_cache_control\n'), ((39, 40, 39, 69), 'urllib.parse.urlparse', 'urlparse', ({(39, 49, 39, 68): 'settings.STATIC_URL'}, {}), '(settings.STATIC_URL)', False, 'from urllib.parse import urlparse\n')]