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

app = Flask(__name__)


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def handle_request(path):
    # Copy the inbound headers so we can modify them before forwarding.
    headers = dict(request.headers)

    # Remove a header from inbound requests. Perhaps your origin server
    # is gzipping responses and you want to stop it doing that.
    headers.pop("Accept-Encoding", None)

    # Add a header to an inbound request before passing it to origin,
    # for example to let origins validate that requests came from the CDN.
    headers["Cdn-Secret"] = "9yfncb340-6abf5oa-ejni22jkdg"

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

    # Copy the response headers, removing the ones we don't want to send
    # back to the browser. Header names are compared case-insensitively,
    # matching HTTP semantics (over HTTP/2 they arrive lowercased).
    resp_headers = [
        (name, value)
        for name, value in backend_response.headers.items()
        if name.lower() not in ("x-amz-request-id", "server")
    ]

    # Add headers to the response back to the browser.
    resp_headers.append(("Cache-Control", "max-age=60"))
    resp_headers.append(("Content-Security-Policy", "default-src 'self'"))

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


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