#include "rtree.h"

#include <limits.h>
#include <stdlib.h>
#include <string.h>

/* ------------------------------------------------------------------ types */

#define MAX_ENTRIES    16
#define MIN_ENTRIES    6
#define MAX_HEIGHT     64
#define SENTINEL       (1 << 24)
#define MAX_VALID_DIST (1LL << 42)
#define FREE_NONE      UINT32_MAX

typedef int32_t  v4i32 __attribute__((vector_size(16)));
typedef uint32_t v4u32 __attribute__((vector_size(16)));

/*
 * 384-byte (3 x 128-byte Apple M3 cache lines) SoA node layout:
 *   CL 0 (0..127):   x0[16], x1[16]
 *   CL 1 (128..255): y0[16], y1[16]
 *   CL 2 (256..383): val[16] (leaf id or child pool index), count, padding
 *
 * Unused slots [count..15] always hold SENTINEL in x0, x1, y0, y1 so all
 * hot queries and ChooseLeaf run fixed 16-lane branchless SIMD loops.
 */
typedef struct {
    _Alignas(128) int32_t x0[MAX_ENTRIES];
    int32_t x1[MAX_ENTRIES];
    int32_t y0[MAX_ENTRIES];
    int32_t y1[MAX_ENTRIES];
    int32_t val[MAX_ENTRIES];
    uint32_t count;
    uint32_t _pad[15];
} Node;

_Static_assert(sizeof(Node) == 384, "Node must be exactly 3 cache lines (384 bytes)");
_Static_assert(_Alignof(Node) == 128, "Node must be 128-byte aligned");

typedef struct {
    int64_t dist;
    uint32_t idx;
    uint32_t lvl;
} PQItem;

typedef struct {
    int64_t dist;
    int32_t id;
} NNItem;

typedef struct {
    int32_t x0, y0, x1, y1, val;
    uint8_t level;
} ReinsertEntry;

struct rtree {
    Node *leaves;
    uint32_t leaf_cap;
    uint32_t leaf_used;
    uint32_t leaf_free_head;

    Node *internals;
    uint32_t int_cap;
    uint32_t int_used;
    uint32_t int_free_head;

    uint32_t root;
    uint32_t height;
    size_t len;
    size_t node_count;

    /* Reusable scratch buffers for rtree_nearest */
    PQItem *pq;
    size_t pq_cap;
    NNItem *nn_res;
    size_t nn_cap;
};

/* ----------------------------------------------------------- SIMD helpers */

static inline v4i32 load_v4(const int32_t *p) {
    v4i32 v;
    memcpy(&v, p, sizeof(v));
    return v;
}

static inline v4i32 splat_v4(int32_t s) {
    return (v4i32){s, s, s, s};
}

static inline bool any4(v4i32 m0, v4i32 m1, v4i32 m2, v4i32 m3) {
    v4u32 c = (v4u32)(m0 | m1 | m2 | m3);
    return (c[0] | c[1] | c[2] | c[3]) != 0;
}

static inline uint32_t movemask4(v4i32 m0, v4i32 m1, v4i32 m2, v4i32 m3) {
    const v4u32 b0 = {1u << 0,  1u << 1,  1u << 2,  1u << 3};
    const v4u32 b1 = {1u << 4,  1u << 5,  1u << 6,  1u << 7};
    const v4u32 b2 = {1u << 8,  1u << 9,  1u << 10, 1u << 11};
    const v4u32 b3 = {1u << 12, 1u << 13, 1u << 14, 1u << 15};
    v4u32 c = ((v4u32)m0 & b0) | ((v4u32)m1 & b1) | ((v4u32)m2 & b2) | ((v4u32)m3 & b3);
    return c[0] + c[1] + c[2] + c[3];
}

static inline void fill_sentinels(Node *n, uint32_t from) {
    for (uint32_t i = from; i < MAX_ENTRIES; i++) {
        n->x0[i] = SENTINEL;
        n->x1[i] = SENTINEL;
        n->y0[i] = SENTINEL;
        n->y1[i] = SENTINEL;
    }
}

static inline void init_empty_node(Node *n) {
    v4i32 vs = splat_v4(SENTINEL);
    for (int g = 0; g < MAX_ENTRIES; g += 4) {
        memcpy(&n->x0[g], &vs, sizeof(vs));
        memcpy(&n->x1[g], &vs, sizeof(vs));
        memcpy(&n->y0[g], &vs, sizeof(vs));
        memcpy(&n->y1[g], &vs, sizeof(vs));
    }
    n->count = 0;
}

/* ----------------------------------------------------------- pool helpers */

static Node *alloc_node_array(uint32_t cap) {
    size_t bytes = (size_t)cap * sizeof(Node);
    void *p = aligned_alloc(128, bytes);
    if (!p) abort();
    return (Node *)p;
}

static uint32_t alloc_leaf(rtree *t) {
    uint32_t idx;
    if (t->leaf_free_head != FREE_NONE) {
        idx = t->leaf_free_head;
        t->leaf_free_head = t->leaves[idx].count;
    } else {
        if (t->leaf_used == t->leaf_cap) {
            uint32_t new_cap = t->leaf_cap ? t->leaf_cap * 2 : 16;
            Node *new_arr = alloc_node_array(new_cap);
            if (t->leaves) {
                memcpy(new_arr, t->leaves, (size_t)t->leaf_used * sizeof(Node));
                free(t->leaves);
            }
            t->leaves = new_arr;
            t->leaf_cap = new_cap;
        }
        idx = t->leaf_used++;
    }
    init_empty_node(&t->leaves[idx]);
    t->node_count++;
    return idx;
}

static uint32_t alloc_internal(rtree *t) {
    uint32_t idx;
    if (t->int_free_head != FREE_NONE) {
        idx = t->int_free_head;
        t->int_free_head = t->internals[idx].count;
    } else {
        if (t->int_used == t->int_cap) {
            uint32_t new_cap = t->int_cap ? t->int_cap * 2 : 8;
            Node *new_arr = alloc_node_array(new_cap);
            if (t->internals) {
                memcpy(new_arr, t->internals, (size_t)t->int_used * sizeof(Node));
                free(t->internals);
            }
            t->internals = new_arr;
            t->int_cap = new_cap;
        }
        idx = t->int_used++;
    }
    init_empty_node(&t->internals[idx]);
    t->node_count++;
    return idx;
}

static inline void free_leaf(rtree *t, uint32_t idx) {
    t->leaves[idx].count = t->leaf_free_head;
    t->leaf_free_head = idx;
    t->node_count--;
}

static inline void free_internal(rtree *t, uint32_t idx) {
    t->internals[idx].count = t->int_free_head;
    t->int_free_head = idx;
    t->node_count--;
}

/* ----------------------------------------------------------- lifecycle */

rtree *rtree_new(void) {
    rtree *t = (rtree *)calloc(1, sizeof(rtree));
    if (!t) abort();
    t->leaf_free_head = FREE_NONE;
    t->int_free_head = FREE_NONE;
    return t;
}

void rtree_free(rtree *t) {
    if (!t) return;
    free(t->leaves);
    free(t->internals);
    free(t->pq);
    free(t->nn_res);
    free(t);
}

size_t rtree_len(const rtree *t) { return t->len; }
size_t rtree_height(const rtree *t) { return t->height; }
size_t rtree_node_count(const rtree *t) { return t->node_count; }

/* ------------------------------------------------------- choose & split */

static inline int choose_child(const Node *n, int32_t rx0, int32_t ry0, int32_t rx1, int32_t ry1) {
    int64_t enl[MAX_ENTRIES];
    int64_t area[MAX_ENTRIES];
    v4i32 vrx0 = splat_v4(rx0);
    v4i32 vrx1 = splat_v4(rx1);
    v4i32 vry0 = splat_v4(ry0);
    v4i32 vry1 = splat_v4(ry1);

    for (int g = 0; g < MAX_ENTRIES; g += 4) {
        v4i32 x0 = load_v4(&n->x0[g]);
        v4i32 x1 = load_v4(&n->x1[g]);
        v4i32 mx0 = x0 < vrx0;
        v4i32 nx0 = (x0 & mx0) | (vrx0 & ~mx0);
        v4i32 mx1 = x1 > vrx1;
        v4i32 nx1 = (x1 & mx1) | (vrx1 & ~mx1);
        v4i32 odx = x1 - x0;
        v4i32 ndx = nx1 - nx0;

        v4i32 y0 = load_v4(&n->y0[g]);
        v4i32 y1 = load_v4(&n->y1[g]);
        v4i32 my0 = y0 < vry0;
        v4i32 ny0 = (y0 & my0) | (vry0 & ~my0);
        v4i32 my1 = y1 > vry1;
        v4i32 ny1 = (y1 & my1) | (vry1 & ~my1);
        v4i32 ody = y1 - y0;
        v4i32 ndy = ny1 - ny0;

        for (int j = 0; j < 4; j++) {
            int64_t a = (int64_t)odx[j] * (int64_t)ody[j];
            int64_t na = (int64_t)ndx[j] * (int64_t)ndy[j];
            area[g + j] = a;
            enl[g + j] = na - a;
        }
    }

    int idx8[8];
    for (int i = 0; i < 8; i++) {
        int a = 2 * i, b = 2 * i + 1;
        bool bw = (enl[b] < enl[a]) | ((enl[b] == enl[a]) & (area[b] < area[a]));
        idx8[i] = bw ? b : a;
    }
    int idx4[4];
    for (int i = 0; i < 4; i++) {
        int a = idx8[2 * i], b = idx8[2 * i + 1];
        bool bw = (enl[b] < enl[a]) | ((enl[b] == enl[a]) & (area[b] < area[a]));
        idx4[i] = bw ? b : a;
    }
    int idx2[2];
    for (int i = 0; i < 2; i++) {
        int a = idx4[2 * i], b = idx4[2 * i + 1];
        bool bw = (enl[b] < enl[a]) | ((enl[b] == enl[a]) & (area[b] < area[a]));
        idx2[i] = bw ? b : a;
    }
    int a = idx2[0], b = idx2[1];
    bool bw = (enl[b] < enl[a]) | ((enl[b] == enl[a]) & (area[b] < area[a]));
    return bw ? b : a;
}

static inline void compute_group_enlargements(
    int32_t gx0, int32_t gy0, int32_t gx1, int32_t gy1, int64_t ga,
    const int32_t *rx0, const int32_t *rx1, const int32_t *ry0, const int32_t *ry1,
    int nrem, int64_t *out_d)
{
    v4i32 vgx0 = splat_v4(gx0);
    v4i32 vgx1 = splat_v4(gx1);
    v4i32 vgy0 = splat_v4(gy0);
    v4i32 vgy1 = splat_v4(gy1);

    for (int g = 0; g < nrem; g += 4) {
        v4i32 x0 = load_v4(&rx0[g]);
        v4i32 x1 = load_v4(&rx1[g]);
        v4i32 mx0 = vgx0 < x0;
        v4i32 nx0 = (vgx0 & mx0) | (x0 & ~mx0);
        v4i32 mx1 = vgx1 > x1;
        v4i32 nx1 = (vgx1 & mx1) | (x1 & ~mx1);
        v4i32 dx = nx1 - nx0;

        v4i32 y0 = load_v4(&ry0[g]);
        v4i32 y1 = load_v4(&ry1[g]);
        v4i32 my0 = vgy0 < y0;
        v4i32 ny0 = (vgy0 & my0) | (y0 & ~my0);
        v4i32 my1 = vgy1 > y1;
        v4i32 ny1 = (vgy1 & my1) | (y1 & ~my1);
        v4i32 dy = ny1 - ny0;

        for (int j = 0; j < 4; j++) {
            out_d[g + j] = (int64_t)dx[j] * (int64_t)dy[j] - ga;
        }
    }
}

/*
 * Quadratic split of full node `n1` (16 entries) plus the 17th entry
 * (nx0, ny0, nx1, ny1, nval) into `n1` and `n2`.
 * Writes exact bounding boxes of `n1` and `n2` to `b1[4]` and `b2[4]`.
 */
static void split_node(Node *n1, Node *n2,
                       int32_t nx0, int32_t ny0, int32_t nx1, int32_t ny1, int32_t nval,
                       int32_t b1[4], int32_t b2[4])
{
    int32_t ex0[17], ex1[17], ey0[17], ey1[17], eval[17];
    int64_t earea[17];

    memcpy(ex0, n1->x0, MAX_ENTRIES * sizeof(int32_t));
    memcpy(ex1, n1->x1, MAX_ENTRIES * sizeof(int32_t));
    memcpy(ey0, n1->y0, MAX_ENTRIES * sizeof(int32_t));
    memcpy(ey1, n1->y1, MAX_ENTRIES * sizeof(int32_t));
    memcpy(eval, n1->val, MAX_ENTRIES * sizeof(int32_t));
    ex0[16] = nx0; ex1[16] = nx1; ey0[16] = ny0; ey1[16] = ny1; eval[16] = nval;

    for (int i = 0; i < 17; i++) {
        earea[i] = (int64_t)(ex1[i] - ex0[i]) * (int64_t)(ey1[i] - ey0[i]);
    }

    /* 1. PickSeeds: maximize area(J) - area(E1) - area(E2) with 4-wide SIMD */
    int64_t best_d = INT64_MIN;
    int seed1 = 0, seed2 = 1;
    int64_t vbuf[16];
    for (int i = 1; i < 17; i++) {
        v4i32 vix0 = splat_v4(ex0[i]);
        v4i32 vix1 = splat_v4(ex1[i]);
        v4i32 viy0 = splat_v4(ey0[i]);
        v4i32 viy1 = splat_v4(ey1[i]);

        for (int g = 0; g < i; g += 4) {
            v4i32 x0 = load_v4(&ex0[g]);
            v4i32 x1 = load_v4(&ex1[g]);
            v4i32 mx0 = vix0 < x0;
            v4i32 jx0 = (vix0 & mx0) | (x0 & ~mx0);
            v4i32 mx1 = vix1 > x1;
            v4i32 jx1 = (vix1 & mx1) | (x1 & ~mx1);
            v4i32 dx = jx1 - jx0;

            v4i32 y0 = load_v4(&ey0[g]);
            v4i32 y1 = load_v4(&ey1[g]);
            v4i32 my0 = viy0 < y0;
            v4i32 jy0 = (viy0 & my0) | (y0 & ~my0);
            v4i32 my1 = viy1 > y1;
            v4i32 jy1 = (viy1 & my1) | (y1 & ~my1);
            v4i32 dy = jy1 - jy0;

            for (int j = 0; j < 4; j++) {
                vbuf[g + j] = (int64_t)dx[j] * (int64_t)dy[j] - earea[g + j];
            }
        }

        uint64_t row_best = 0;
        for (int j = 0; j < i; j++) {
            /* area(J) >= earea[j] always, so vbuf[j] in [0, 2^40) */
            uint64_t packed = ((uint64_t)vbuf[j] << 4) | (uint64_t)j;
            if (packed > row_best) row_best = packed;
        }
        int64_t d = (int64_t)(row_best >> 4) - earea[i];
        if (d > best_d) {
            best_d = d;
            seed1 = (int)(row_best & 15);
            seed2 = i;
        }
    }

    /* Place seeds into group 1 (n1) and group 2 (n2) */
    int32_t g1x0 = ex0[seed1], g1x1 = ex1[seed1], g1y0 = ey0[seed1], g1y1 = ey1[seed1];
    int64_t a1 = earea[seed1];
    n1->x0[0] = g1x0; n1->x1[0] = g1x1; n1->y0[0] = g1y0; n1->y1[0] = g1y1;
    n1->val[0] = eval[seed1];
    int c1 = 1;

    int32_t g2x0 = ex0[seed2], g2x1 = ex1[seed2], g2y0 = ey0[seed2], g2y1 = ey1[seed2];
    int64_t a2 = earea[seed2];
    n2->x0[0] = g2x0; n2->x1[0] = g2x1; n2->y0[0] = g2y0; n2->y1[0] = g2y1;
    n2->val[0] = eval[seed2];
    int c2 = 1;

    /* Compact remaining 15 entries (slot 15 zeroed for 4-wide SIMD reads) */
    int32_t rx0[16], rx1[16], ry0[16], ry1[16], rval[16];
    int nrem = 0;
    for (int i = 0; i < 17; i++) {
        if (i == seed1 || i == seed2) continue;
        rx0[nrem] = ex0[i];
        rx1[nrem] = ex1[i];
        ry0[nrem] = ey0[i];
        ry1[nrem] = ey1[i];
        rval[nrem] = eval[i];
        nrem++;
    }
    rx0[15] = rx1[15] = ry0[15] = ry1[15] = 0;

    int64_t d1[16], d2[16];
    compute_group_enlargements(g1x0, g1y0, g1x1, g1y1, a1, rx0, rx1, ry0, ry1, nrem, d1);
    compute_group_enlargements(g2x0, g2y0, g2x1, g2y1, a2, rx0, rx1, ry0, ry1, nrem, d2);

    /* 2. PickNext with incremental enlargement updates */
    while (nrem > 0) {
        if (c1 + nrem == MIN_ENTRIES) {
            for (int i = 0; i < nrem; i++) {
                int32_t x0 = rx0[i], x1 = rx1[i], y0 = ry0[i], y1 = ry1[i];
                n1->x0[c1] = x0; n1->x1[c1] = x1; n1->y0[c1] = y0; n1->y1[c1] = y1;
                n1->val[c1] = rval[i];
                c1++;
                if (x0 < g1x0) g1x0 = x0;
                if (x1 > g1x1) g1x1 = x1;
                if (y0 < g1y0) g1y0 = y0;
                if (y1 > g1y1) g1y1 = y1;
            }
            break;
        }
        if (c2 + nrem == MIN_ENTRIES) {
            for (int i = 0; i < nrem; i++) {
                int32_t x0 = rx0[i], x1 = rx1[i], y0 = ry0[i], y1 = ry1[i];
                n2->x0[c2] = x0; n2->x1[c2] = x1; n2->y0[c2] = y0; n2->y1[c2] = y1;
                n2->val[c2] = rval[i];
                c2++;
                if (x0 < g2x0) g2x0 = x0;
                if (x1 > g2x1) g2x1 = x1;
                if (y0 < g2y0) g2y0 = y0;
                if (y1 > g2y1) g2y1 = y1;
            }
            break;
        }

        uint64_t best_packed = 0;
        for (int i = 0; i < nrem; i++) {
            int64_t diff = d1[i] >= d2[i] ? (d1[i] - d2[i]) : (d2[i] - d1[i]);
            uint64_t packed = ((uint64_t)diff << 4) | (uint64_t)i;
            if (packed > best_packed) best_packed = packed;
        }
        int k = (int)(best_packed & 15);

        int64_t e1 = d1[k], e2 = d2[k];
        bool to_g1 = (e1 < e2) || (e1 == e2 && (a1 < a2 || (a1 == a2 && c1 <= c2)));

        int32_t kx0 = rx0[k], kx1 = rx1[k], ky0 = ry0[k], ky1 = ry1[k], kval = rval[k];
        nrem--;
        if (k != nrem) {
            rx0[k] = rx0[nrem]; rx1[k] = rx1[nrem];
            ry0[k] = ry0[nrem]; ry1[k] = ry1[nrem];
            rval[k] = rval[nrem];
            d1[k] = d1[nrem]; d2[k] = d2[nrem];
        }

        if (to_g1) {
            n1->x0[c1] = kx0; n1->x1[c1] = kx1; n1->y0[c1] = ky0; n1->y1[c1] = ky1;
            n1->val[c1] = kval;
            c1++;
            bool changed = (kx0 < g1x0) | (kx1 > g1x1) | (ky0 < g1y0) | (ky1 > g1y1);
            if (changed) {
                if (kx0 < g1x0) g1x0 = kx0;
                if (kx1 > g1x1) g1x1 = kx1;
                if (ky0 < g1y0) g1y0 = ky0;
                if (ky1 > g1y1) g1y1 = ky1;
                a1 = (int64_t)(g1x1 - g1x0) * (int64_t)(g1y1 - g1y0);
                compute_group_enlargements(g1x0, g1y0, g1x1, g1y1, a1, rx0, rx1, ry0, ry1, nrem, d1);
            }
        } else {
            n2->x0[c2] = kx0; n2->x1[c2] = kx1; n2->y0[c2] = ky0; n2->y1[c2] = ky1;
            n2->val[c2] = kval;
            c2++;
            bool changed = (kx0 < g2x0) | (kx1 > g2x1) | (ky0 < g2y0) | (ky1 > g2y1);
            if (changed) {
                if (kx0 < g2x0) g2x0 = kx0;
                if (kx1 > g2x1) g2x1 = kx1;
                if (ky0 < g2y0) g2y0 = ky0;
                if (ky1 > g2y1) g2y1 = ky1;
                a2 = (int64_t)(g2x1 - g2x0) * (int64_t)(g2y1 - g2y0);
                compute_group_enlargements(g2x0, g2y0, g2x1, g2y1, a2, rx0, rx1, ry0, ry1, nrem, d2);
            }
        }
    }

    n1->count = (uint32_t)c1;
    n2->count = (uint32_t)c2;
    fill_sentinels(n1, (uint32_t)c1);
    fill_sentinels(n2, (uint32_t)c2);

    b1[0] = g1x0; b1[1] = g1y0; b1[2] = g1x1; b1[3] = g1y1;
    b2[0] = g2x0; b2[1] = g2y0; b2[2] = g2x1; b2[3] = g2y1;
}

/* -------------------------------------------------------------- insert */

static void insert_at_level(rtree *t, int32_t rx0, int32_t ry0, int32_t rx1, int32_t ry1,
                            int32_t val, uint32_t target_level)
{
    uint32_t path_idx[MAX_HEIGHT];
    int path_slot[MAX_HEIGHT];

    uint32_t cur = t->root;
    uint32_t lvl = t->height - 1;

    /* Top-down ChooseNode with immediate exact bbox expansion */
    while (lvl > target_level) {
        Node *n = &t->internals[cur];
        int best = choose_child(n, rx0, ry0, rx1, ry1);
        path_idx[lvl] = cur;
        path_slot[lvl] = best;

        n->x0[best] = rx0 < n->x0[best] ? rx0 : n->x0[best];
        n->x1[best] = rx1 > n->x1[best] ? rx1 : n->x1[best];
        n->y0[best] = ry0 < n->y0[best] ? ry0 : n->y0[best];
        n->y1[best] = ry1 > n->y1[best] ? ry1 : n->y1[best];

        cur = (uint32_t)n->val[best];
        lvl--;
    }

    /* Insert at target_level */
    Node *target = (target_level == 0) ? &t->leaves[cur] : &t->internals[cur];
    if (__builtin_expect(target->count < MAX_ENTRIES, 1)) {
        uint32_t pos = target->count++;
        target->x0[pos] = rx0;
        target->x1[pos] = rx1;
        target->y0[pos] = ry0;
        target->y1[pos] = ry1;
        target->val[pos] = val;
        return;
    }

    /* Overflow: split and propagate splits upward (ancestors above last split already exact!) */
    int32_t b1[4], b2[4];
    uint32_t new_idx;
    if (target_level == 0) {
        new_idx = alloc_leaf(t); /* may realloc t->leaves */
        split_node(&t->leaves[cur], &t->leaves[new_idx], rx0, ry0, rx1, ry1, val, b1, b2);
    } else {
        new_idx = alloc_internal(t); /* may realloc t->internals */
        split_node(&t->internals[cur], &t->internals[new_idx], rx0, ry0, rx1, ry1, val, b1, b2);
    }

    uint32_t split_lvl = target_level;
    while (split_lvl + 1 < t->height) {
        uint32_t parent_idx = path_idx[split_lvl + 1];
        int pslot = path_slot[split_lvl + 1];
        Node *parent = &t->internals[parent_idx];

        /* Update left half bbox in parent */
        parent->x0[pslot] = b1[0];
        parent->y0[pslot] = b1[1];
        parent->x1[pslot] = b1[2];
        parent->y1[pslot] = b1[3];

        if (parent->count < MAX_ENTRIES) {
            uint32_t pos = parent->count++;
            parent->x0[pos] = b2[0];
            parent->y0[pos] = b2[1];
            parent->x1[pos] = b2[2];
            parent->y1[pos] = b2[3];
            parent->val[pos] = (int32_t)new_idx;
            return;
        }

        /* Parent also overflows -> split parent */
        uint32_t new_parent = alloc_internal(t); /* may realloc t->internals */
        int32_t pb1[4], pb2[4];
        split_node(&t->internals[parent_idx], &t->internals[new_parent],
                   b2[0], b2[1], b2[2], b2[3], (int32_t)new_idx, pb1, pb2);
        memcpy(b1, pb1, sizeof(b1));
        memcpy(b2, pb2, sizeof(b2));
        cur = parent_idx;
        new_idx = new_parent;
        split_lvl++;
    }

    /* Root split -> create new internal root */
    uint32_t new_root = alloc_internal(t);
    Node *rn = &t->internals[new_root];
    rn->x0[0] = b1[0]; rn->y0[0] = b1[1]; rn->x1[0] = b1[2]; rn->y1[0] = b1[3];
    rn->val[0] = (int32_t)cur;
    rn->x0[1] = b2[0]; rn->y0[1] = b2[1]; rn->x1[1] = b2[2]; rn->y1[1] = b2[3];
    rn->val[1] = (int32_t)new_idx;
    rn->count = 2;
    t->root = new_root;
    t->height++;
}

void rtree_insert(rtree *t, int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    if (__builtin_expect(t->height == 0, 0)) {
        uint32_t root = alloc_leaf(t);
        Node *rn = &t->leaves[root];
        rn->x0[0] = x0; rn->x1[0] = x1; rn->y0[0] = y0; rn->y1[0] = y1;
        rn->val[0] = id;
        rn->count = 1;
        t->root = root;
        t->height = 1;
        t->len = 1;
        return;
    }
    insert_at_level(t, x0, y0, x1, y1, id, 0);
    t->len++;
}

/* -------------------------------------------------------------- remove */

static inline void compute_bbox(const Node *n, int32_t *ox0, int32_t *oy0, int32_t *ox1, int32_t *oy1) {
    uint32_t cnt = n->count;
    int32_t bx0 = n->x0[0], bx1 = n->x1[0];
    int32_t by0 = n->y0[0], by1 = n->y1[0];
    for (uint32_t i = 1; i < cnt; i++) {
        if (n->x0[i] < bx0) bx0 = n->x0[i];
        if (n->x1[i] > bx1) bx1 = n->x1[i];
        if (n->y0[i] < by0) by0 = n->y0[i];
        if (n->y1[i] > by1) by1 = n->y1[i];
    }
    *ox0 = bx0; *oy0 = by0; *ox1 = bx1; *oy1 = by1;
}

static int find_leaf(const rtree *t, uint32_t idx, uint32_t lvl,
                     int32_t rx0, int32_t ry0, int32_t rx1, int32_t ry1, int32_t id,
                     uint32_t *path_idx, int *path_slot)
{
    v4i32 vrx0 = splat_v4(rx0);
    v4i32 vrx1 = splat_v4(rx1);
    v4i32 vry0 = splat_v4(ry0);
    v4i32 vry1 = splat_v4(ry1);

    if (lvl == 0) {
        const Node *n = &t->leaves[idx];
        v4i32 mx0 = (load_v4(&n->x0[0])  == vrx0) & (load_v4(&n->x1[0])  == vrx1);
        v4i32 mx1 = (load_v4(&n->x0[4])  == vrx0) & (load_v4(&n->x1[4])  == vrx1);
        v4i32 mx2 = (load_v4(&n->x0[8])  == vrx0) & (load_v4(&n->x1[8])  == vrx1);
        v4i32 mx3 = (load_v4(&n->x0[12]) == vrx0) & (load_v4(&n->x1[12]) == vrx1);
        if (!any4(mx0, mx1, mx2, mx3)) return -1;

        v4i32 m0 = mx0 & (load_v4(&n->y0[0])  == vry0) & (load_v4(&n->y1[0])  == vry1);
        v4i32 m1 = mx1 & (load_v4(&n->y0[4])  == vry0) & (load_v4(&n->y1[4])  == vry1);
        v4i32 m2 = mx2 & (load_v4(&n->y0[8])  == vry0) & (load_v4(&n->y1[8])  == vry1);
        v4i32 m3 = mx3 & (load_v4(&n->y0[12]) == vry0) & (load_v4(&n->y1[12]) == vry1);
        uint32_t mask = movemask4(m0, m1, m2, m3);
        while (mask) {
            int i = __builtin_ctz(mask);
            mask &= mask - 1;
            if (n->val[i] == id) {
                path_idx[0] = idx;
                return i;
            }
        }
        return -1;
    }

    const Node *n = &t->internals[idx];
    v4i32 mx0 = (load_v4(&n->x0[0])  <= vrx0) & (vrx1 <= load_v4(&n->x1[0]));
    v4i32 mx1 = (load_v4(&n->x0[4])  <= vrx0) & (vrx1 <= load_v4(&n->x1[4]));
    v4i32 mx2 = (load_v4(&n->x0[8])  <= vrx0) & (vrx1 <= load_v4(&n->x1[8]));
    v4i32 mx3 = (load_v4(&n->x0[12]) <= vrx0) & (vrx1 <= load_v4(&n->x1[12]));
    if (!any4(mx0, mx1, mx2, mx3)) return -1;

    v4i32 m0 = mx0 & (load_v4(&n->y0[0])  <= vry0) & (vry1 <= load_v4(&n->y1[0]));
    v4i32 m1 = mx1 & (load_v4(&n->y0[4])  <= vry0) & (vry1 <= load_v4(&n->y1[4]));
    v4i32 m2 = mx2 & (load_v4(&n->y0[8])  <= vry0) & (vry1 <= load_v4(&n->y1[8]));
    v4i32 m3 = mx3 & (load_v4(&n->y0[12]) <= vry0) & (vry1 <= load_v4(&n->y1[12]));
    uint32_t mask = movemask4(m0, m1, m2, m3);
    if (!mask) return -1;

    path_idx[lvl] = idx;
    if (lvl == 1 && (mask & (mask - 1))) {
        uint32_t pm = mask;
        while (pm) {
            int i = __builtin_ctz(pm);
            pm &= pm - 1;
            __builtin_prefetch(&t->leaves[(uint32_t)n->val[i]].x0[0], 0, 1);
        }
    }
    while (mask) {
        int i = __builtin_ctz(mask);
        mask &= mask - 1;
        path_slot[lvl] = i;
        int found = find_leaf(t, (uint32_t)n->val[i], lvl - 1,
                              rx0, ry0, rx1, ry1, id, path_idx, path_slot);
        if (found >= 0) return found;
    }
    return -1;
}

bool rtree_remove(rtree *t, int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    if (__builtin_expect(t->height == 0, 0)) return false;

    uint32_t path_idx[MAX_HEIGHT];
    int path_slot[MAX_HEIGHT];
    int slot = find_leaf(t, t->root, t->height - 1, x0, y0, x1, y1, id, path_idx, path_slot);
    if (slot < 0) return false;

    /* Remove entry from leaf */
    uint32_t leaf_idx = path_idx[0];
    Node *leaf = &t->leaves[leaf_idx];
    uint32_t last = --leaf->count;
    if ((uint32_t)slot != last) {
        leaf->x0[slot] = leaf->x0[last];
        leaf->x1[slot] = leaf->x1[last];
        leaf->y0[slot] = leaf->y0[last];
        leaf->y1[slot] = leaf->y1[last];
        leaf->val[slot] = leaf->val[last];
    }
    leaf->x0[last] = SENTINEL;
    leaf->x1[last] = SENTINEL;
    leaf->y0[last] = SENTINEL;
    leaf->y1[last] = SENTINEL;
    t->len--;

    if (t->height == 1) {
        if (leaf->count == 0) {
            free_leaf(t, leaf_idx);
            t->root = 0;
            t->height = 0;
        }
        return true;
    }

    /* Fast path: leaf did not underflow and removed rect was strictly inside leaf's bbox */
    if (leaf->count >= MIN_ENTRIES) {
        Node *parent = &t->internals[path_idx[1]];
        int pslot = path_slot[1];
        if (x0 > parent->x0[pslot] && x1 < parent->x1[pslot] &&
            y0 > parent->y0[pslot] && y1 < parent->y1[pslot]) {
            return true;
        }
    }

    /* CondenseTree */
    ReinsertEntry q[MAX_HEIGHT * MIN_ENTRIES];
    uint32_t qlen = 0;
    uint32_t H = t->height;

    for (uint32_t lvl = 0; lvl < H - 1; lvl++) {
        uint32_t cur_idx = path_idx[lvl];
        uint32_t parent_idx = path_idx[lvl + 1];
        int pslot = path_slot[lvl + 1];
        Node *cur = (lvl == 0) ? &t->leaves[cur_idx] : &t->internals[cur_idx];
        Node *parent = &t->internals[parent_idx];

        if (cur->count < MIN_ENTRIES) {
            for (uint32_t i = 0; i < cur->count; i++) {
                q[qlen++] = (ReinsertEntry){
                    cur->x0[i], cur->y0[i], cur->x1[i], cur->y1[i], cur->val[i], (uint8_t)lvl
                };
            }
            if (lvl == 0) free_leaf(t, cur_idx);
            else free_internal(t, cur_idx);

            uint32_t plast = --parent->count;
            if ((uint32_t)pslot != plast) {
                parent->x0[pslot] = parent->x0[plast];
                parent->x1[pslot] = parent->x1[plast];
                parent->y0[pslot] = parent->y0[plast];
                parent->y1[pslot] = parent->y1[plast];
                parent->val[pslot] = parent->val[plast];
            }
            parent->x0[plast] = SENTINEL;
            parent->x1[plast] = SENTINEL;
            parent->y0[plast] = SENTINEL;
            parent->y1[plast] = SENTINEL;
        } else {
            int32_t bx0, by0, bx1, by1;
            compute_bbox(cur, &bx0, &by0, &bx1, &by1);
            if (bx0 == parent->x0[pslot] && bx1 == parent->x1[pslot] &&
                by0 == parent->y0[pslot] && by1 == parent->y1[pslot]) {
                break;
            }
            parent->x0[pslot] = bx0;
            parent->y0[pslot] = by0;
            parent->x1[pslot] = bx1;
            parent->y1[pslot] = by1;
        }
    }

    /* Reinsert set-aside entries at their original levels (highest level first) */
    for (uint32_t i = qlen; i-- > 0; ) {
        insert_at_level(t, q[i].x0, q[i].y0, q[i].x1, q[i].y1, q[i].val, q[i].level);
    }

    /* Shrink root while internal root has only one child */
    while (t->height > 1 && t->internals[t->root].count == 1) {
        uint32_t old_root = t->root;
        t->root = (uint32_t)t->internals[old_root].val[0];
        free_internal(t, old_root);
        t->height--;
    }

    return true;
}

/* -------------------------------------------------------------- search */

static inline size_t dump_subtree(const rtree *t, uint32_t idx, uint32_t lvl,
                                  int32_t *out_ids, size_t cap, size_t total)
{
    if (lvl == 0) {
        const Node *leaf = &t->leaves[idx];
        uint32_t cnt = leaf->count;
        if (__builtin_expect(total + cnt <= cap, 1)) {
            memcpy(out_ids + total, leaf->val, (size_t)cnt * sizeof(int32_t));
        } else if (total < cap) {
            memcpy(out_ids + total, leaf->val, (cap - total) * sizeof(int32_t));
        }
        return total + cnt;
    }

    uint32_t s_idx[1024];
    uint8_t  s_lvl[1024];
    int sp = 0;
    s_idx[sp] = idx;
    s_lvl[sp] = (uint8_t)lvl;
    sp++;

    while (sp > 0) {
        sp--;
        uint32_t cur = s_idx[sp];
        uint32_t clvl = s_lvl[sp];
        const Node *n = &t->internals[cur];
        uint32_t cnt = n->count;

        if (clvl == 1) {
            /* Prefetch CL2 (val + count) of all child leaves — never touch CL0/CL1! */
            for (uint32_t i = 0; i < cnt; i++) {
                __builtin_prefetch(&t->leaves[(uint32_t)n->val[i]].val[0], 0, 1);
            }
            for (uint32_t i = 0; i < cnt; i++) {
                const Node *leaf = &t->leaves[(uint32_t)n->val[i]];
                uint32_t lcnt = leaf->count;
                if (__builtin_expect(total + lcnt <= cap, 1)) {
                    memcpy(out_ids + total, leaf->val, (size_t)lcnt * sizeof(int32_t));
                } else if (total < cap) {
                    memcpy(out_ids + total, leaf->val, (cap - total) * sizeof(int32_t));
                }
                total += lcnt;
            }
        } else {
            for (uint32_t i = 0; i < cnt; i++) {
                s_idx[sp] = (uint32_t)n->val[i];
                s_lvl[sp] = (uint8_t)(clvl - 1);
                sp++;
            }
        }
    }
    return total;
}

static inline size_t scan_leaf_window(const Node *leaf,
                                      v4i32 vqx0, v4i32 vqy0, v4i32 vqx1, v4i32 vqy1,
                                      int32_t *out_ids, size_t cap, size_t total)
{
    v4i32 mx0 = (load_v4(&leaf->x0[0])  <= vqx1) & (vqx0 <= load_v4(&leaf->x1[0]));
    v4i32 mx1 = (load_v4(&leaf->x0[4])  <= vqx1) & (vqx0 <= load_v4(&leaf->x1[4]));
    v4i32 mx2 = (load_v4(&leaf->x0[8])  <= vqx1) & (vqx0 <= load_v4(&leaf->x1[8]));
    v4i32 mx3 = (load_v4(&leaf->x0[12]) <= vqx1) & (vqx0 <= load_v4(&leaf->x1[12]));
    if (!any4(mx0, mx1, mx2, mx3)) return total;

    v4i32 m0 = mx0 & (load_v4(&leaf->y0[0])  <= vqy1) & (vqy0 <= load_v4(&leaf->y1[0]));
    v4i32 m1 = mx1 & (load_v4(&leaf->y0[4])  <= vqy1) & (vqy0 <= load_v4(&leaf->y1[4]));
    v4i32 m2 = mx2 & (load_v4(&leaf->y0[8])  <= vqy1) & (vqy0 <= load_v4(&leaf->y1[8]));
    v4i32 m3 = mx3 & (load_v4(&leaf->y0[12]) <= vqy1) & (vqy0 <= load_v4(&leaf->y1[12]));
    uint32_t mask = movemask4(m0, m1, m2, m3);
    if (!mask) return total;

    if (__builtin_expect(total + MAX_ENTRIES <= cap, 1)) {
        while (mask) {
            int i = __builtin_ctz(mask);
            mask &= mask - 1;
            out_ids[total++] = leaf->val[i];
        }
    } else {
        while (mask) {
            int i = __builtin_ctz(mask);
            mask &= mask - 1;
            if (total < cap) out_ids[total] = leaf->val[i];
            total++;
        }
    }
    return total;
}

static size_t search_point(const rtree *t, int32_t px, int32_t py, int32_t *out_ids, size_t cap) {
    v4i32 vpx = splat_v4(px);
    v4i32 vpy = splat_v4(py);

    if (t->height == 1) {
        return scan_leaf_window(&t->leaves[t->root], vpx, vpy, vpx, vpy, out_ids, cap, 0);
    }

    uint32_t s_idx[1024];
    uint8_t  s_lvl[1024];
    int sp = 0;
    s_idx[sp] = t->root;
    s_lvl[sp] = (uint8_t)(t->height - 1);
    sp++;

    size_t total = 0;
    while (sp > 0) {
        sp--;
        uint32_t cur = s_idx[sp];
        uint32_t clvl = s_lvl[sp];
        const Node *n = &t->internals[cur];

        v4i32 mx0 = (load_v4(&n->x0[0])  <= vpx) & (vpx <= load_v4(&n->x1[0]));
        v4i32 mx1 = (load_v4(&n->x0[4])  <= vpx) & (vpx <= load_v4(&n->x1[4]));
        v4i32 mx2 = (load_v4(&n->x0[8])  <= vpx) & (vpx <= load_v4(&n->x1[8]));
        v4i32 mx3 = (load_v4(&n->x0[12]) <= vpx) & (vpx <= load_v4(&n->x1[12]));
        if (!any4(mx0, mx1, mx2, mx3)) continue;

        v4i32 m0 = mx0 & (load_v4(&n->y0[0])  <= vpy) & (vpy <= load_v4(&n->y1[0]));
        v4i32 m1 = mx1 & (load_v4(&n->y0[4])  <= vpy) & (vpy <= load_v4(&n->y1[4]));
        v4i32 m2 = mx2 & (load_v4(&n->y0[8])  <= vpy) & (vpy <= load_v4(&n->y1[8]));
        v4i32 m3 = mx3 & (load_v4(&n->y0[12]) <= vpy) & (vpy <= load_v4(&n->y1[12]));
        uint32_t mask = movemask4(m0, m1, m2, m3);
        if (!mask) continue;

        if (clvl == 1) {
            if (mask & (mask - 1)) {
                uint32_t pm = mask;
                while (pm) {
                    int i = __builtin_ctz(pm);
                    pm &= pm - 1;
                    const Node *lf = &t->leaves[(uint32_t)n->val[i]];
                    __builtin_prefetch(&lf->x0[0], 0, 1);
                    __builtin_prefetch(&lf->y0[0], 0, 1);
                }
            }
            while (mask) {
                int i = __builtin_ctz(mask);
                mask &= mask - 1;
                total = scan_leaf_window(&t->leaves[(uint32_t)n->val[i]],
                                         vpx, vpy, vpx, vpy, out_ids, cap, total);
            }
        } else {
            uint8_t next_lvl = (uint8_t)(clvl - 1);
            while (mask) {
                int i = __builtin_ctz(mask);
                mask &= mask - 1;
                s_idx[sp] = (uint32_t)n->val[i];
                s_lvl[sp] = next_lvl;
                sp++;
            }
        }
    }
    return total;
}

size_t rtree_search(const rtree *t, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
                    int32_t *out_ids, size_t cap)
{
    if (__builtin_expect(t->height == 0, 0)) return 0;

    if (x0 == x1 && y0 == y1) {
        return search_point(t, x0, y0, out_ids, cap);
    }

    v4i32 vqx0 = splat_v4(x0);
    v4i32 vqy0 = splat_v4(y0);
    v4i32 vqx1 = splat_v4(x1);
    v4i32 vqy1 = splat_v4(y1);

    if (t->height == 1) {
        return scan_leaf_window(&t->leaves[t->root], vqx0, vqy0, vqx1, vqy1, out_ids, cap, 0);
    }

    uint32_t s_idx[1024];
    uint8_t  s_lvl[1024];
    int sp = 0;
    s_idx[sp] = t->root;
    s_lvl[sp] = (uint8_t)(t->height - 1);
    sp++;

    size_t total = 0;
    while (sp > 0) {
        sp--;
        uint32_t cur = s_idx[sp];
        uint32_t clvl = s_lvl[sp];
        const Node *n = &t->internals[cur];

        v4i32 vx0_0 = load_v4(&n->x0[0]),  vx1_0 = load_v4(&n->x1[0]);
        v4i32 vx0_1 = load_v4(&n->x0[4]),  vx1_1 = load_v4(&n->x1[4]);
        v4i32 vx0_2 = load_v4(&n->x0[8]),  vx1_2 = load_v4(&n->x1[8]);
        v4i32 vx0_3 = load_v4(&n->x0[12]), vx1_3 = load_v4(&n->x1[12]);

        v4i32 mx0 = (vx0_0 <= vqx1) & (vqx0 <= vx1_0);
        v4i32 mx1 = (vx0_1 <= vqx1) & (vqx0 <= vx1_1);
        v4i32 mx2 = (vx0_2 <= vqx1) & (vqx0 <= vx1_2);
        v4i32 mx3 = (vx0_3 <= vqx1) & (vqx0 <= vx1_3);
        if (!any4(mx0, mx1, mx2, mx3)) continue;

        v4i32 vy0_0 = load_v4(&n->y0[0]),  vy1_0 = load_v4(&n->y1[0]);
        v4i32 vy0_1 = load_v4(&n->y0[4]),  vy1_1 = load_v4(&n->y1[4]);
        v4i32 vy0_2 = load_v4(&n->y0[8]),  vy1_2 = load_v4(&n->y1[8]);
        v4i32 vy0_3 = load_v4(&n->y0[12]), vy1_3 = load_v4(&n->y1[12]);

        v4i32 m0 = mx0 & (vy0_0 <= vqy1) & (vqy0 <= vy1_0);
        v4i32 m1 = mx1 & (vy0_1 <= vqy1) & (vqy0 <= vy1_1);
        v4i32 m2 = mx2 & (vy0_2 <= vqy1) & (vqy0 <= vy1_2);
        v4i32 m3 = mx3 & (vy0_3 <= vqy1) & (vqy0 <= vy1_3);
        uint32_t mask = movemask4(m0, m1, m2, m3);
        if (!mask) continue;

        /* Check which matching children are completely contained in query */
        v4i32 c0 = m0 & (vqx0 <= vx0_0) & (vx1_0 <= vqx1) & (vqy0 <= vy0_0) & (vy1_0 <= vqy1);
        v4i32 c1 = m1 & (vqx0 <= vx0_1) & (vx1_1 <= vqx1) & (vqy0 <= vy0_1) & (vy1_1 <= vqy1);
        v4i32 c2 = m2 & (vqx0 <= vx0_2) & (vx1_2 <= vqx1) & (vqy0 <= vy0_2) & (vy1_2 <= vqy1);
        v4i32 c3 = m3 & (vqx0 <= vx0_3) & (vx1_3 <= vqx1) & (vqy0 <= vy0_3) & (vy1_3 <= vqy1);
        uint32_t cmask = movemask4(c0, c1, c2, c3);
        uint32_t pmask = mask & ~cmask;

        if (clvl == 1) {
            /* Prefetch matching leaves in parallel when >= 2 leaves match */
            if (mask & (mask - 1)) {
                uint32_t pm = cmask;
                while (pm) {
                    int i = __builtin_ctz(pm);
                    pm &= pm - 1;
                    __builtin_prefetch(&t->leaves[(uint32_t)n->val[i]].val[0], 0, 1);
                }
                pm = pmask;
                while (pm) {
                    int i = __builtin_ctz(pm);
                    pm &= pm - 1;
                    const Node *lf = &t->leaves[(uint32_t)n->val[i]];
                    __builtin_prefetch(&lf->x0[0], 0, 1);
                    __builtin_prefetch(&lf->y0[0], 0, 1);
                }
            }
            while (cmask) {
                int i = __builtin_ctz(cmask);
                cmask &= cmask - 1;
                const Node *leaf = &t->leaves[(uint32_t)n->val[i]];
                uint32_t cnt = leaf->count;
                if (__builtin_expect(total + cnt <= cap, 1)) {
                    memcpy(out_ids + total, leaf->val, (size_t)cnt * sizeof(int32_t));
                } else if (total < cap) {
                    memcpy(out_ids + total, leaf->val, (cap - total) * sizeof(int32_t));
                }
                total += cnt;
            }
            while (pmask) {
                int i = __builtin_ctz(pmask);
                pmask &= pmask - 1;
                total = scan_leaf_window(&t->leaves[(uint32_t)n->val[i]],
                                         vqx0, vqy0, vqx1, vqy1, out_ids, cap, total);
            }
        } else {
            uint32_t next_lvl = clvl - 1;
            while (cmask) {
                int i = __builtin_ctz(cmask);
                cmask &= cmask - 1;
                total = dump_subtree(t, (uint32_t)n->val[i], next_lvl, out_ids, cap, total);
            }
            while (pmask) {
                int i = __builtin_ctz(pmask);
                pmask &= pmask - 1;
                s_idx[sp] = (uint32_t)n->val[i];
                s_lvl[sp] = (uint8_t)next_lvl;
                sp++;
            }
        }
    }
    return total;
}

/* ------------------------------------------------------------- nearest */

static inline void compute_dists(const Node *n, int32_t px, int32_t py, int64_t dist[MAX_ENTRIES]) {
    v4i32 vpx = splat_v4(px);
    v4i32 vpy = splat_v4(py);
    v4i32 vzero = {0, 0, 0, 0};

    for (int g = 0; g < MAX_ENTRIES; g += 4) {
        v4i32 x0 = load_v4(&n->x0[g]);
        v4i32 x1 = load_v4(&n->x1[g]);
        v4i32 d1 = x0 - vpx;
        v4i32 d2 = vpx - x1;
        v4i32 m1 = d1 > d2;
        v4i32 dx = (d1 & m1) | (d2 & ~m1);
        dx = dx & (dx > vzero);

        v4i32 y0 = load_v4(&n->y0[g]);
        v4i32 y1 = load_v4(&n->y1[g]);
        v4i32 d3 = y0 - vpy;
        v4i32 d4 = vpy - y1;
        v4i32 m2 = d3 > d4;
        v4i32 dy = (d3 & m2) | (d4 & ~m2);
        dy = dy & (dy > vzero);

        for (int j = 0; j < 4; j++) {
            int64_t vx = dx[j];
            int64_t vy = dy[j];
            dist[g + j] = vx * vx + vy * vy;
        }
    }
}

/* 4-ary min-heap for candidate tree nodes */
static inline void pq_ensure(rtree *t, size_t need) {
    if (__builtin_expect(need <= t->pq_cap, 1)) return;
    size_t new_cap = t->pq_cap ? t->pq_cap * 2 : 256;
    while (new_cap < need) new_cap *= 2;
    PQItem *p = (PQItem *)realloc(t->pq, new_cap * sizeof(PQItem));
    if (!p) abort();
    t->pq = p;
    t->pq_cap = new_cap;
}

static inline void pq_push(rtree *t, size_t *pq_len, int64_t dist, uint32_t idx, uint32_t lvl) {
    size_t n = *pq_len;
    pq_ensure(t, n + 1);
    PQItem *pq = t->pq;
    while (n > 0) {
        size_t parent = (n - 1) >> 2;
        if (pq[parent].dist <= dist) break;
        pq[n] = pq[parent];
        n = parent;
    }
    pq[n].dist = dist;
    pq[n].idx = idx;
    pq[n].lvl = lvl;
    (*pq_len)++;
}

static inline PQItem pq_pop(PQItem *pq, size_t *pq_len) {
    PQItem top = pq[0];
    size_t n = --(*pq_len);
    if (n > 0) {
        PQItem item = pq[n];
        size_t i = 0;
        for (;;) {
            size_t c = (i << 2) + 1;
            if (c >= n) break;
            size_t best = c;
            int64_t best_d = pq[c].dist;
            size_t end = c + 4 < n ? c + 4 : n;
            for (size_t j = c + 1; j < end; j++) {
                if (pq[j].dist < best_d) {
                    best_d = pq[j].dist;
                    best = j;
                }
            }
            if (item.dist <= best_d) break;
            pq[i] = pq[best];
            i = best;
        }
        pq[i] = item;
    }
    return top;
}

/* Binary max-heap for top-k leaf entries, ordered by (dist, id) */
static inline bool nn_worse(NNItem a, NNItem b) {
    return (a.dist > b.dist) || (a.dist == b.dist && a.id > b.id);
}

static inline void nn_push(NNItem *heap, size_t *len, int64_t dist, int32_t id) {
    size_t i = (*len)++;
    NNItem item = {dist, id};
    while (i > 0) {
        size_t p = (i - 1) >> 1;
        if (!nn_worse(item, heap[p])) break;
        heap[i] = heap[p];
        i = p;
    }
    heap[i] = item;
}

static inline void nn_sift_down(NNItem *heap, size_t len, NNItem item) {
    size_t i = 0;
    for (;;) {
        size_t l = (i << 1) + 1;
        if (l >= len) break;
        size_t r = l + 1;
        size_t best = (r < len && nn_worse(heap[r], heap[l])) ? r : l;
        if (!nn_worse(heap[best], item)) break;
        heap[i] = heap[best];
        i = best;
    }
    heap[i] = item;
}

static inline void prefetch_pq_top(const rtree *t, size_t pq_len, int64_t limit) {
    if (pq_len > 0 && t->pq[0].dist <= limit) {
        const Node *pn = (t->pq[0].lvl == 0) ? &t->leaves[t->pq[0].idx]
                                             : &t->internals[t->pq[0].idx];
        __builtin_prefetch(&pn->x0[0], 0, 1);
        __builtin_prefetch(&pn->y0[0], 0, 1);
    }
}

static size_t nearest_one(rtree *t, int32_t px, int32_t py, int32_t *out_ids) {
    int64_t best_dist = MAX_VALID_DIST;
    int32_t best_id = INT32_MAX;

    if (t->height == 1) {
        int64_t dist[MAX_ENTRIES];
        const Node *leaf = &t->leaves[t->root];
        compute_dists(leaf, px, py, dist);
        for (int i = 0; i < MAX_ENTRIES; i++) {
            int64_t d = dist[i];
            if (__builtin_expect(d <= best_dist, 0)) {
                int32_t id = leaf->val[i];
                if (d < best_dist || id < best_id) {
                    best_dist = d;
                    best_id = id;
                }
            }
        }
        out_ids[0] = best_id;
        return 1;
    }

    size_t pq_len = 0;
    uint32_t cur_idx = t->root;
    uint32_t cur_lvl = t->height - 1;

    for (;;) {
        if (cur_lvl == 0) {
            prefetch_pq_top(t, pq_len, best_dist);
            int64_t dist[MAX_ENTRIES];
            const Node *leaf = &t->leaves[cur_idx];
            compute_dists(leaf, px, py, dist);
            for (int i = 0; i < MAX_ENTRIES; i++) {
                int64_t d = dist[i];
                if (__builtin_expect(d <= best_dist, 0)) {
                    int32_t id = leaf->val[i];
                    if (d < best_dist || id < best_id) {
                        best_dist = d;
                        best_id = id;
                    }
                }
            }
            if (pq_len == 0) break;
            PQItem next = pq_pop(t->pq, &pq_len);
            if (next.dist > best_dist) break;
            cur_idx = next.idx;
            cur_lvl = next.lvl;
        } else {
            int64_t dist[MAX_ENTRIES];
            const Node *n = &t->internals[cur_idx];
            compute_dists(n, px, py, dist);

            int best_c = -1;
            int64_t min_d = best_dist;
            for (int i = 0; i < MAX_ENTRIES; i++) {
                if (dist[i] <= min_d) {
                    if (best_c < 0 || dist[i] < min_d) {
                        min_d = dist[i];
                        best_c = i;
                    }
                }
            }

            if (best_c >= 0) {
                uint32_t child_lvl = cur_lvl - 1;
                int64_t pq_top_d = pq_len > 0 ? t->pq[0].dist : INT64_MAX;

                if (child_lvl == 0 && min_d <= pq_top_d) {
                    prefetch_pq_top(t, pq_len, best_dist);
                    int64_t ldist[MAX_ENTRIES];
                    const Node *leaf = &t->leaves[(uint32_t)n->val[best_c]];
                    compute_dists(leaf, px, py, ldist);
                    for (int i = 0; i < MAX_ENTRIES; i++) {
                        int64_t d = ldist[i];
                        if (__builtin_expect(d <= best_dist, 0)) {
                            int32_t id = leaf->val[i];
                            if (d < best_dist || id < best_id) {
                                best_dist = d;
                                best_id = id;
                            }
                        }
                    }
                    for (int i = 0; i < MAX_ENTRIES; i++) {
                        if (i != best_c && dist[i] <= best_dist) {
                            pq_push(t, &pq_len, dist[i], (uint32_t)n->val[i], 0);
                        }
                    }
                    if (pq_len == 0) break;
                    PQItem next = pq_pop(t->pq, &pq_len);
                    if (next.dist > best_dist) break;
                    cur_idx = next.idx;
                    cur_lvl = next.lvl;
                } else {
                    if (min_d > pq_top_d) prefetch_pq_top(t, pq_len, best_dist);
                    for (int i = 0; i < MAX_ENTRIES; i++) {
                        if (i != best_c && dist[i] <= best_dist) {
                            pq_push(t, &pq_len, dist[i], (uint32_t)n->val[i], child_lvl);
                        }
                    }
                    if (min_d <= pq_top_d) {
                        cur_idx = (uint32_t)n->val[best_c];
                        cur_lvl = child_lvl;
                    } else {
                        pq_push(t, &pq_len, min_d, (uint32_t)n->val[best_c], child_lvl);
                        PQItem next = pq_pop(t->pq, &pq_len);
                        if (next.dist > best_dist) break;
                        cur_idx = next.idx;
                        cur_lvl = next.lvl;
                    }
                }
            } else {
                if (pq_len == 0) break;
                PQItem next = pq_pop(t->pq, &pq_len);
                if (next.dist > best_dist) break;
                cur_idx = next.idx;
                cur_lvl = next.lvl;
            }
        }
    }

    out_ids[0] = best_id;
    return 1;
}

static inline void scan_leaf_nn(const Node *leaf, int32_t px, int32_t py,
                                NNItem *res, size_t *res_len, size_t eff_k,
                                int64_t *thresh_dist, int32_t *thresh_id)
{
    int64_t dist[MAX_ENTRIES];
    compute_dists(leaf, px, py, dist);
    int64_t td = *thresh_dist;
    int32_t tid = *thresh_id;
    size_t rlen = *res_len;

    if (__builtin_expect(rlen == eff_k, 1)) {
        for (int i = 0; i < MAX_ENTRIES; i++) {
            int64_t d = dist[i];
            if (__builtin_expect(d <= td, 0)) {
                int32_t id = leaf->val[i];
                if (d < td || id < tid) {
                    nn_sift_down(res, eff_k, (NNItem){d, id});
                    td = res[0].dist;
                    tid = res[0].id;
                }
            }
        }
    } else {
        for (int i = 0; i < MAX_ENTRIES; i++) {
            int64_t d = dist[i];
            if (d > td) continue;
            if (rlen < eff_k) {
                if (d >= MAX_VALID_DIST) continue;
                nn_push(res, &rlen, d, leaf->val[i]);
                if (rlen == eff_k) {
                    td = res[0].dist;
                    tid = res[0].id;
                }
            } else {
                int32_t id = leaf->val[i];
                if (d < td || (d == td && id < tid)) {
                    nn_sift_down(res, eff_k, (NNItem){d, id});
                    td = res[0].dist;
                    tid = res[0].id;
                }
            }
        }
    }

    *res_len = rlen;
    *thresh_dist = td;
    *thresh_id = tid;
}

size_t rtree_nearest(rtree *t, int32_t x, int32_t y, size_t k, int32_t *out_ids) {
    if (__builtin_expect(k == 0 || t->len == 0, 0)) return 0;

    size_t eff_k = k < t->len ? k : t->len;
    if (eff_k == 1) {
        return nearest_one(t, x, y, out_ids);
    }

    if (eff_k > t->nn_cap) {
        size_t new_cap = t->nn_cap ? t->nn_cap * 2 : 32;
        while (new_cap < eff_k) new_cap *= 2;
        NNItem *p = (NNItem *)realloc(t->nn_res, new_cap * sizeof(NNItem));
        if (!p) abort();
        t->nn_res = p;
        t->nn_cap = new_cap;
    }

    NNItem *res = t->nn_res;
    size_t res_len = 0;
    int64_t thresh_dist = MAX_VALID_DIST;
    int32_t thresh_id = INT32_MAX;

    if (t->height == 1) {
        scan_leaf_nn(&t->leaves[t->root], x, y, res, &res_len, eff_k, &thresh_dist, &thresh_id);
    } else {
        size_t pq_len = 0;
        uint32_t cur_idx = t->root;
        uint32_t cur_lvl = t->height - 1;

        for (;;) {
            if (cur_lvl == 0) {
                prefetch_pq_top(t, pq_len, (res_len == eff_k) ? thresh_dist : MAX_VALID_DIST);
                scan_leaf_nn(&t->leaves[cur_idx], x, y, res, &res_len, eff_k, &thresh_dist, &thresh_id);
                if (pq_len == 0) break;
                PQItem next = pq_pop(t->pq, &pq_len);
                if (res_len == eff_k && next.dist > thresh_dist) break;
                cur_idx = next.idx;
                cur_lvl = next.lvl;
            } else {
                int64_t dist[MAX_ENTRIES];
                const Node *n = &t->internals[cur_idx];
                compute_dists(n, x, y, dist);

                int64_t limit = (res_len == eff_k) ? thresh_dist : (MAX_VALID_DIST - 1);
                int best_c = -1;
                int64_t min_d = limit;
                for (int i = 0; i < MAX_ENTRIES; i++) {
                    if (dist[i] <= min_d) {
                        if (best_c < 0 || dist[i] < min_d) {
                            min_d = dist[i];
                            best_c = i;
                        }
                    }
                }

                if (best_c >= 0) {
                    uint32_t child_lvl = cur_lvl - 1;
                    int64_t pq_top_d = pq_len > 0 ? t->pq[0].dist : INT64_MAX;

                    if (child_lvl == 0 && min_d <= pq_top_d) {
                        prefetch_pq_top(t, pq_len, limit);
                        scan_leaf_nn(&t->leaves[(uint32_t)n->val[best_c]], x, y,
                                     res, &res_len, eff_k, &thresh_dist, &thresh_id);
                        int64_t new_lim = (res_len == eff_k) ? thresh_dist : (MAX_VALID_DIST - 1);
                        for (int i = 0; i < MAX_ENTRIES; i++) {
                            if (i != best_c && dist[i] <= new_lim) {
                                pq_push(t, &pq_len, dist[i], (uint32_t)n->val[i], 0);
                            }
                        }
                        if (pq_len == 0) break;
                        PQItem next = pq_pop(t->pq, &pq_len);
                        if (res_len == eff_k && next.dist > thresh_dist) break;
                        cur_idx = next.idx;
                        cur_lvl = next.lvl;
                    } else {
                        if (min_d > pq_top_d) prefetch_pq_top(t, pq_len, limit);
                        for (int i = 0; i < MAX_ENTRIES; i++) {
                            if (i != best_c && dist[i] <= limit) {
                                pq_push(t, &pq_len, dist[i], (uint32_t)n->val[i], child_lvl);
                            }
                        }
                        if (min_d <= pq_top_d) {
                            cur_idx = (uint32_t)n->val[best_c];
                            cur_lvl = child_lvl;
                        } else {
                            pq_push(t, &pq_len, min_d, (uint32_t)n->val[best_c], child_lvl);
                            PQItem next = pq_pop(t->pq, &pq_len);
                            if (res_len == eff_k && next.dist > thresh_dist) break;
                            cur_idx = next.idx;
                            cur_lvl = next.lvl;
                        }
                    }
                } else {
                    if (pq_len == 0) break;
                    PQItem next = pq_pop(t->pq, &pq_len);
                    if (res_len == eff_k && next.dist > thresh_dist) break;
                    cur_idx = next.idx;
                    cur_lvl = next.lvl;
                }
            }
        }
    }

    /* Extract max-heap back-to-front into ascending (dist, id) order */
    size_t count = res_len;
    for (size_t i = count; i-- > 0; ) {
        out_ids[i] = res[0].id;
        res_len--;
        if (res_len > 0) {
            nn_sift_down(res, res_len, res[res_len]);
        }
    }
    return count;
}
