import re
from urllib.parse import urlsplit, urlunsplit

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

app = Flask(__name__)

# Match the incoming path against a pattern.
PATH_MATCH = re.compile(r"^/some-(custom|dynamic|complex)-pattern/url/path$")


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def handle_request(path):
    # Parse the request URL so we can rewrite just the path.
    parts = urlsplit(request.url)
    new_path = parts.path

    # If the URL matches the pattern, rewrite the path that we send
    # to origin, without issuing a redirect to the client.
    if PATH_MATCH.match(parts.path):
        new_path = "/status/200"

    origin_url = urlunsplit(
        (parts.scheme, parts.netloc, new_path, parts.query, parts.fragment)
    )

    # Send the (possibly rewritten) request to origin.
    backend_response = requests.request(
        request.method,
        origin_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)