from urllib.parse import urlparse, urlunparse

def split_base_uri_containers(uri):
    """
    Splits the base uri from the containers and returns both base uri and a container list.
    This assumes that the given uri contains an api version string, metadata and container names
    # separated by slashes, e.g. api/v1/metadata/masks/special_container
    """
    parsed_url = urlparse(uri)
    path = parsed_url.path
    # Path is either empty or contains a leading slash only
    if len(path) < 2:
        return uri, []

    # Check if the path contain an api string that could be followed by containers
    if "/api" not in path:
        return uri, []

    # TODO: Allow more flexible splitting of the path, using other api endpoints
    path_pieces = path.split("/metadata", 1)
    base_uri = urlunparse(
        (
            parsed_url.scheme,
            parsed_url.netloc,
            path_pieces[0],
            parsed_url.params,
            parsed_url.query,
            parsed_url.fragment,
        )
    )
    container_names = (
        path_pieces[1].strip("/").split("/") if len(path_pieces) > 1 else []
    )
    return base_uri, container_names