from fastly_compute import requests
from fastly_compute.wsgi import WsgiHttpIncoming
from flask import Flask, request

app = Flask(__name__)


@app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"])
@app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"])
def handle_request(path):
    # Change PUT requests to POST requests before sending to origin.
    method = "POST" if request.method == "PUT" else request.method

    # Send the request to origin using the (possibly changed) method.
    backend_response = requests.request(
        method,
        request.url,
        headers=dict(request.headers),
        data=request.get_data(),
        fastly_backend="origin_0",
    )

    return (
        backend_response.content,
        backend_response.status_code,
        backend_response.headers,
    )


# This is the entry point Fastly Compute looks for.
HttpIncoming = WsgiHttpIncoming(app)