import typing as t


class ApiApiFix:
    """
    Combine multiple applications as a single WSGI application.
    Requests are dispatched to an application based on the path it is
    mounted under.

    Parameters
    ----------

    app: WSGIApplication

        The WSGI application to dispatch to if the request
        doesn't match a mounted path.

    mounts: t.Dict[str, "WSGIApplication"]

        Maps path prefixes to applications for dispatching.

    """

    def __init__(self, app: "WSGIApplication" = None) -> None:
        self.next = None
        if app:
            self.init_app(app)

    def init_app(self, app: "WSGIApplication") -> None:
        self.next = app.wsgi_app
        app.wsgi_app = self

        return app

    def __call__(self, environ: "WSGIEnvironment", start_response: "StartResponse") -> t.Iterable[bytes]:
        script = environ.get("PATH_INFO", "")
        if script.startswith("/api/api/"):
            script = script[4:]
            environ["PATH_INFO"] = script

        return self.next(environ, start_response)
