#include <algorithm>
#include <iostream>
#include <iterator>
#include <string_view>
#include <utility>
#include <vector>

#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/version.hpp>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

using Point = bg::model::d2::point_xy<double>;
using Path = bg::model::linestring<Point>;
using Box = bg::model::box<Point>;
using Entry = std::pair<Box, std::size_t>;

int main() {
    static_assert(BOOST_VERSION == 108800, "This demo pins Boost 1.88.0");
    const std::vector<Path> paths{
        {{1, 1}, {9, 9}},
        {{0, 9}, {9, 9}},
        {{12, 12}, {16, 12}},
        {{18, 14}, {21, 15}},
    };
    const std::vector<std::string_view> labels{
        "diagonal", "horizontal", "far-a", "far-b",
    };

    // A small node capacity makes the tree split even for this tiny fixture.
    bgi::rtree<Entry, bgi::quadratic<2>> index;
    for (std::size_t id = 0; id < paths.size(); ++id) {
        index.insert({bg::return_envelope<Box>(paths[id]), id});
    }

    const Box marquee{{0, 8}, {2, 10}};
    std::vector<Entry> candidates;
    index.query(bgi::intersects(marquee), std::back_inserter(candidates));
    std::sort(candidates.begin(), candidates.end(),
              [](const Entry& a, const Entry& b) { return a.second < b.second; });

    std::cout << "Boost " << BOOST_VERSION / 100000 << '.'
              << BOOST_VERSION / 100 % 1000 << '.' << BOOST_VERSION % 100 << '\n';
    for (const auto& entry : candidates) {
        const auto id = entry.second;
        std::cout << labels[id] << ": "
                  << (bg::intersects(paths[id], marquee) ? "hit" : "box only")
                  << '\n';
    }
}
