#include <fastly/sdk.h>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <ada.h>

int main(int argc, char* argv[]) {
    // Get the request from the client.
    auto req = fastly::Request::from_client();

    std::string surrogate_keys;

    // Parse the URL using the WHATWG-compliant ada-url library.
    auto url_obj = ada::parse<ada::url_aggregator>(req.get_url());

    if (!url_obj || url_obj->get_pathname().empty()) {
        surrogate_keys = "/";
    } else {
        auto pathname = url_obj->get_pathname();

        size_t last_slash_pos = 0;

        while (true) {
            auto slash_pos = pathname.find_first_of('/', last_slash_pos + 1);

            if (!surrogate_keys.empty()) {
                surrogate_keys += " ";
            }
 
            if (slash_pos == std::string_view::npos) {
                surrogate_keys += pathname;
                break;
            }

            surrogate_keys += pathname.substr(0, slash_pos);
            last_slash_pos = slash_pos;
        }
    }

    // Log surrogate keys for testing.
    std::cout << surrogate_keys << std::endl;

    // Send the request to the backend, applying the surrogate keys.
    auto _ = req.set_surrogate_key(surrogate_keys);
    auto backend_response = req.send("http_me");

    // Send the backend response back to the client.
    backend_response->send_to_client();

    return 0;
}