from django.conf import settings
from django.urls import resolve
from django.utils import translation
from django.middleware.locale import LocaleMiddleware


class NoCacheUiPagesMiddleware:
    """Never let browsers (esp. iOS Safari's heuristic cache) serve stale UI pages.

    Deployments change templates frequently; without an explicit Cache-Control
    Safari may cache the HTML heuristically and users keep seeing the previous
    version even after a fix ships ("did you fix it? still broken"). UI pages
    are cheap to render; always fetch fresh.
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if request.path.startswith('/ui/') and response.get('Content-Type', '').startswith('text/html'):
            response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
        return response


class CustomLocaleMiddleware(LocaleMiddleware):
    def process_request(self, request):
        url_path = request.path_info.lstrip('/')

        # 检查是否是 API 路径
        if url_path.startswith('api/'):
            return None

        return super().process_request(request)
