class ReverseProxied(object):
    """
    This middleware is based on the following snippet:
    From http://flask.pocoo.org/snippets/35/

    Our services live behind reverse proxies which operate like so:
        https://[fully-qualified-domain-name]/[service-prefix]/[service-endpoint]
    which gets reverse proxied to
        http://[internal-service]/[service-endpoint]

    As a result of this, URLs generated by Flask are missing the vital [service-rest-prefix].
    Our services are RESTful and function largely by generating fully qualified URLs, so
    this renders them unusable.

        EXAMPLE:

              https://platform-cluster.wuxinextcodedev.com/api/query/query/6/

            is proxied to:

              http://plat-query-api/query/6/

            which generates a self link of the form:

              https://platform-cluster.wuxinextcodedev.com/query/6/

            Which will return a 404

    To remedy this, we need to forward the [service-prefix] from the proxy in the form of a
    HTTP Header.

    That header is then picked up by this middleware which notifies Flask
"""

    # There is no standard header. Everybody is just making stuff up and madness reigns.
    # We hard-code the headers we know - and allow overrides via the
    # PROXY_PREFIX config variable, which will use the prefix value instead of inspecting headers.
    proxy_prefix_headers = (
        "HTTP_X_REPLACED_PATH",  # AWS ALB
        "HTTP_X_FORWARDED_PREFIX",  # traefik
        "WXNC_RESTFUL_PREFIX",  # nginx inside PLAT service containers
    )

    def __init__(self, app):
        self.app = app.wsgi_app
        self.config = app.config
        self.proxy_prefix = self.config.get("PROXY_PREFIX")

    def get_proxy_prefix(self, environ):
        if self.proxy_prefix:
            return self.proxy_prefix

        for header in self.proxy_prefix_headers:
            if environ.get(header):
                return environ.get(header)
        else:
            return None

    def patch_environ(self, environ, rest_prefix):
        if rest_prefix:
            environ["SCRIPT_NAME"] = rest_prefix
            path_info = environ.get("PATH_INFO", "")
            if path_info.startswith(rest_prefix):
                ln = len(rest_prefix)
                environ["PATH_INFO"] = path_info[ln:]
        return environ

    def __call__(self, environ, start_response):
        rest_prefix = self.get_proxy_prefix(environ)
        environ = self.patch_environ(environ, rest_prefix)
        return self.app(environ, start_response)
