from django.http import Http404, HttpResponseRedirect
from django.urls import resolve


class BlogRedirectMiddleware:
    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)

        # Check if the response is 404 and not a request for /blog/
        if (response.status_code == 404 and
                not (request.path.startswith('/blog/') or request.path.startswith('/media/'))):
            new_path = f'/blog{request.path}'
            try:
                # Check if the new URL with /blog/ exists
                resolve(new_path)
                # Redirect to the new URL if it exists
                return HttpResponseRedirect(new_path)
            except Http404:
                # If the new URL doesn't exist, return the original 404 response
                pass

        return response
