#include <geos_c.h>

#include <iostream>
#include <memory>
#include <stdexcept>
#include <string_view>

int main() try {
    if (std::string_view(GEOSversion()).substr(0, 7) != "3.15.1-") {
        throw std::runtime_error("This demo pins GEOS 3.15.1");
    }

    const auto finish = [](GEOSContextHandle_t handle) { GEOS_finish_r(handle); };
    const std::unique_ptr<GEOSContextHandle_HS, decltype(finish)>
        context(GEOS_init_r(), finish);
    if (!context) throw std::runtime_error("Could not create GEOS context");
    const auto handle = context.get();

    const auto destroyReader = [handle](GEOSWKTReader* reader) {
        GEOSWKTReader_destroy_r(handle, reader);
    };
    const std::unique_ptr<GEOSWKTReader, decltype(destroyReader)>
        reader(GEOSWKTReader_create_r(handle), destroyReader);
    if (!reader) throw std::runtime_error("Could not create WKT reader");

    const auto destroyGeometry = [handle](GEOSGeometry* geometry) {
        GEOSGeom_destroy_r(handle, geometry);
    };
    const auto read = [&](const char* wkt) {
        return std::unique_ptr<GEOSGeometry, decltype(destroyGeometry)>(
            GEOSWKTReader_read_r(handle, reader.get(), wkt), destroyGeometry);
    };

    const auto plate = read("POLYGON ((0 0, 12 0, 12 10, 0 10, 0 0))");
    const auto keepOut = read("POLYGON ((3 3, 9 3, 9 7, 3 7, 3 3))");
    if (!plate || !keepOut ||
        GEOSisValid_r(handle, plate.get()) != 1 ||
        GEOSisValid_r(handle, keepOut.get()) != 1) {
        throw std::runtime_error("Invalid input");
    }

    const std::unique_ptr<GEOSGeometry, decltype(destroyGeometry)> result(
        GEOSDifference_r(handle, plate.get(), keepOut.get()), destroyGeometry);
    double area = 0;
    if (!result || GEOSGeomTypeId_r(handle, result.get()) != GEOS_POLYGON ||
        GEOSisValid_r(handle, result.get()) != 1 ||
        GEOSArea_r(handle, result.get(), &area) != 1) {
        throw std::runtime_error("Unexpected difference result");
    }
    const int holes = GEOSGetNumInteriorRings_r(handle, result.get());
    if (holes < 0) throw std::runtime_error("Could not count interior rings");

    std::cout << "GEOS " << GEOSversion() << '\n'
              << "type=Polygon valid=yes interior_rings=" << holes
              << " area=" << area << '\n';
    return area == 96 && holes == 1 ? 0 : 1;
} catch (const std::exception& error) {
    std::cerr << error.what() << '\n';
    return 1;
}
