// Guttman R-tree (quadratic split), M = 16, m = 6.
//
// Nodes live in one pool (array of fixed 384-byte, 128-byte-aligned nodes)
// addressed by 32-bit index. Each node stores its entries as structure of
// arrays: x0[16], y0[16], x1[16], y1[16] (two cache lines) followed by
// ref[16] (leaf: id, internal: child index), count and level (third line).
// Unused slots hold an "impossible" sentinel rectangle (x0 = y0 = INT32_MAX,
// x1 = y1 = -1) so that query masks can always be computed over all 16 slots
// without looking at the count.

#include "rtree.h"

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

#define MAXE 16
#define MINE 6
#define NIL 0xFFFFFFFFu
#define MAXDEPTH 64

typedef struct {
    int32_t x0, y0, x1, y1;
} rect;

typedef struct node {
    int32_t x0[MAXE], y0[MAXE], x1[MAXE], y1[MAXE];
    int32_t ref[MAXE];
    int32_t count;
    int32_t level;  // 0 = leaf
    uint32_t next_free;
    int32_t pad[13];
} node;

_Static_assert(sizeof(node) == 384, "node size");

struct rtree {
    node *nodes;
    uint32_t ncap, nused, free_head;
    uint32_t root;
    size_t len;
    // nearest scratch
    uint64_t *hd;
    uint32_t *hn;
    size_t hcap;
    uint64_t *rd;
    int32_t *rid;
    size_t rcap;
};

static inline int32_t imin(int32_t a, int32_t b) { return a < b ? a : b; }
static inline int32_t imax(int32_t a, int32_t b) { return a > b ? a : b; }

static inline int64_t rarea(int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
    return (int64_t)(x1 - x0) * (int64_t)(y1 - y0);
}

static void *xmalloc(size_t sz) {
    void *p = malloc(sz ? sz : 1);
    if (!p) abort();
    return p;
}

// ------------------------------------------------------------------ pool

static void node_clear(node *n, int level) {
    for (int i = 0; i < MAXE; i++) {
        n->x0[i] = INT32_MAX;
        n->y0[i] = INT32_MAX;
        n->x1[i] = -1;
        n->y1[i] = -1;
        n->ref[i] = 0;
    }
    n->count = 0;
    n->level = level;
}

static uint32_t node_alloc(rtree *t, int level) {
    uint32_t i;
    if (t->free_head != NIL) {
        i = t->free_head;
        t->free_head = t->nodes[i].next_free;
    } else {
        if (t->nused == t->ncap) {
            uint32_t nc = t->ncap ? t->ncap * 2 : 64;
            node *p = aligned_alloc(128, (size_t)nc * sizeof(node));
            if (!p) abort();
            if (t->nused) memcpy(p, t->nodes, (size_t)t->nused * sizeof(node));
            free(t->nodes);
            t->nodes = p;
            t->ncap = nc;
        }
        i = t->nused++;
    }
    node_clear(&t->nodes[i], level);
    return i;
}

static inline void node_free(rtree *t, uint32_t i) {
    t->nodes[i].next_free = t->free_head;
    t->free_head = i;
}

// ------------------------------------------------------------- node helpers

static inline rect node_bbox(const node *n) {
    int32_t a = INT32_MAX, b = INT32_MAX, c = -1, d = -1;
    for (int i = 0; i < MAXE; i++) {
        a = imin(a, n->x0[i]);
        b = imin(b, n->y0[i]);
        c = imax(c, n->x1[i]);
        d = imax(d, n->y1[i]);
    }
    return (rect){a, b, c, d};
}

static inline void node_set(node *n, int i, rect r, int32_t ref) {
    n->x0[i] = r.x0;
    n->y0[i] = r.y0;
    n->x1[i] = r.x1;
    n->y1[i] = r.y1;
    n->ref[i] = ref;
}

static inline void node_set_rect(node *n, int i, rect r) {
    n->x0[i] = r.x0;
    n->y0[i] = r.y0;
    n->x1[i] = r.x1;
    n->y1[i] = r.y1;
}

static inline void node_remove_slot(node *n, int i) {
    int last = --n->count;
    n->x0[i] = n->x0[last];
    n->y0[i] = n->y0[last];
    n->x1[i] = n->x1[last];
    n->y1[i] = n->y1[last];
    n->ref[i] = n->ref[last];
    n->x0[last] = INT32_MAX;
    n->y0[last] = INT32_MAX;
    n->x1[last] = -1;
    n->y1[last] = -1;
}

static inline uint32_t isect_mask(const node *n, int32_t qx0, int32_t qy0, int32_t qx1, int32_t qy1) {
    uint32_t m = 0;
    for (int i = 0; i < MAXE; i++) {
        uint32_t b = (uint32_t)((n->x0[i] <= qx1) & (n->x1[i] >= qx0) & (n->y0[i] <= qy1) & (n->y1[i] >= qy0));
        m |= b << i;
    }
    return m;
}

static inline uint32_t contain_mask(const node *n, rect r) {
    uint32_t m = 0;
    for (int i = 0; i < MAXE; i++) {
        uint32_t b = (uint32_t)((n->x0[i] <= r.x0) & (n->y0[i] <= r.y0) & (n->x1[i] >= r.x1) & (n->y1[i] >= r.y1));
        m |= b << i;
    }
    return m;
}

static inline uint32_t exact_mask(const node *n, rect r, int32_t id) {
    uint32_t m = 0;
    for (int i = 0; i < MAXE; i++) {
        uint32_t b = (uint32_t)((n->x0[i] == r.x0) & (n->y0[i] == r.y0) & (n->x1[i] == r.x1) & (n->y1[i] == r.y1) &
                                (n->ref[i] == id));
        m |= b << i;
    }
    return m;
}

static inline void prefetch_node(const node *n) {
    const char *p = (const char *)n;
    __builtin_prefetch(p);
    __builtin_prefetch(p + 128);
    __builtin_prefetch(p + 256);
}

// Child needing least enlargement, ties by smallest area.
static inline int choose_subtree(const node *n, rect r) {
    int64_t enl[MAXE], area[MAXE];
    for (int i = 0; i < MAXE; i++) {
        int64_t w = (int64_t)n->x1[i] - n->x0[i];
        int64_t h = (int64_t)n->y1[i] - n->y0[i];
        int64_t a = w * h;
        int64_t ew = (int64_t)imax(n->x1[i], r.x1) - imin(n->x0[i], r.x0);
        int64_t eh = (int64_t)imax(n->y1[i], r.y1) - imin(n->y0[i], r.y0);
        area[i] = a;
        enl[i] = ew * eh - a;
    }
    int best = 0;
    int64_t be = enl[0], ba = area[0];
    int cnt = n->count;
    for (int i = 1; i < cnt; i++) {
        int64_t e = enl[i], a = area[i];
        if (e < be || (e == be && a < ba)) {
            best = i;
            be = e;
            ba = a;
        }
    }
    return best;
}

// ------------------------------------------------------------------- split

// Node ni holds 16 entries; together with (er, eref) they are split by the
// quadratic algorithm into ni and a new node, whose index is returned. b1/b2
// receive the bounding rectangles of ni and of the new node.
static uint32_t split_node(rtree *t, uint32_t ni, rect er, int32_t eref, rect *b1, rect *b2) {
    enum { N = MAXE + 1 };
    int32_t X0[N], Y0[N], X1[N], Y1[N], R[N];
    int64_t A[N];
    {
        const node *n = &t->nodes[ni];
        for (int i = 0; i < MAXE; i++) {
            X0[i] = n->x0[i];
            Y0[i] = n->y0[i];
            X1[i] = n->x1[i];
            Y1[i] = n->y1[i];
            R[i] = n->ref[i];
        }
    }
    X0[MAXE] = er.x0;
    Y0[MAXE] = er.y0;
    X1[MAXE] = er.x1;
    Y1[MAXE] = er.y1;
    R[MAXE] = eref;
    for (int i = 0; i < N; i++) A[i] = rarea(X0[i], Y0[i], X1[i], Y1[i]);

    // PickSeeds
    int s1 = 0, s2 = 1;
    int64_t bd = INT64_MIN;
    for (int i = 0; i < N - 1; i++) {
        for (int j = i + 1; j < N; j++) {
            int64_t d = rarea(imin(X0[i], X0[j]), imin(Y0[i], Y0[j]), imax(X1[i], X1[j]), imax(Y1[i], Y1[j])) -
                        A[i] - A[j];
            if (d > bd) {
                bd = d;
                s1 = i;
                s2 = j;
            }
        }
    }

    uint8_t grp[N];
    memset(grp, 0, sizeof grp);
    grp[s1] = 1;
    grp[s2] = 2;
    rect g1 = {X0[s1], Y0[s1], X1[s1], Y1[s1]};
    rect g2 = {X0[s2], Y0[s2], X1[s2], Y1[s2]};
    int64_t a1 = A[s1], a2 = A[s2];
    int c1 = 1, c2 = 1;
    int rem = N - 2;

    while (rem > 0) {
        if (c1 + rem <= MINE) {
            for (int i = 0; i < N; i++)
                if (!grp[i]) {
                    grp[i] = 1;
                    g1.x0 = imin(g1.x0, X0[i]);
                    g1.y0 = imin(g1.y0, Y0[i]);
                    g1.x1 = imax(g1.x1, X1[i]);
                    g1.y1 = imax(g1.y1, Y1[i]);
                }
            c1 += rem;
            break;
        }
        if (c2 + rem <= MINE) {
            for (int i = 0; i < N; i++)
                if (!grp[i]) {
                    grp[i] = 2;
                    g2.x0 = imin(g2.x0, X0[i]);
                    g2.y0 = imin(g2.y0, Y0[i]);
                    g2.x1 = imax(g2.x1, X1[i]);
                    g2.y1 = imax(g2.y1, Y1[i]);
                }
            c2 += rem;
            break;
        }
        // PickNext
        int bi = -1;
        int64_t bdiff = -1, bd1 = 0, bd2 = 0;
        for (int i = 0; i < N; i++) {
            if (grp[i]) continue;
            int64_t d1 = rarea(imin(g1.x0, X0[i]), imin(g1.y0, Y0[i]), imax(g1.x1, X1[i]), imax(g1.y1, Y1[i])) - a1;
            int64_t d2 = rarea(imin(g2.x0, X0[i]), imin(g2.y0, Y0[i]), imax(g2.x1, X1[i]), imax(g2.y1, Y1[i])) - a2;
            int64_t diff = d1 > d2 ? d1 - d2 : d2 - d1;
            if (diff > bdiff) {
                bdiff = diff;
                bi = i;
                bd1 = d1;
                bd2 = d2;
            }
        }
        int to;
        if (bd1 < bd2) to = 1;
        else if (bd2 < bd1) to = 2;
        else if (a1 < a2) to = 1;
        else if (a2 < a1) to = 2;
        else if (c1 <= c2) to = 1;
        else to = 2;
        grp[bi] = (uint8_t)to;
        rem--;
        if (to == 1) {
            g1.x0 = imin(g1.x0, X0[bi]);
            g1.y0 = imin(g1.y0, Y0[bi]);
            g1.x1 = imax(g1.x1, X1[bi]);
            g1.y1 = imax(g1.y1, Y1[bi]);
            a1 = rarea(g1.x0, g1.y0, g1.x1, g1.y1);
            c1++;
        } else {
            g2.x0 = imin(g2.x0, X0[bi]);
            g2.y0 = imin(g2.y0, Y0[bi]);
            g2.x1 = imax(g2.x1, X1[bi]);
            g2.y1 = imax(g2.y1, Y1[bi]);
            a2 = rarea(g2.x0, g2.y0, g2.x1, g2.y1);
            c2++;
        }
    }

    int level = t->nodes[ni].level;
    uint32_t nni = node_alloc(t, level);  // may move the pool
    node *n = &t->nodes[ni];
    node *nn = &t->nodes[nni];
    node_clear(n, level);
    int k1 = 0, k2 = 0;
    for (int i = 0; i < N; i++) {
        rect r = {X0[i], Y0[i], X1[i], Y1[i]};
        if (grp[i] == 1) node_set(n, k1++, r, R[i]);
        else node_set(nn, k2++, r, R[i]);
    }
    n->count = k1;
    nn->count = k2;
    *b1 = g1;
    *b2 = g2;
    return nni;
}

// ------------------------------------------------------------------ insert

// Insert an entry (r, ref) into a node at the given level (0 = leaf).
static void insert_at(rtree *t, rect r, int32_t ref, int level) {
    uint32_t path[MAXDEPTH];
    int slot[MAXDEPTH];
    int d = 0;
    uint32_t ni = t->root;
    node *n = &t->nodes[ni];
    while (n->level > level) {
        int i = choose_subtree(n, r);
        // Enlarge on the way down: exact unless a split happens below, in
        // which case the entry is recomputed on the way back up.
        n->x0[i] = imin(n->x0[i], r.x0);
        n->y0[i] = imin(n->y0[i], r.y0);
        n->x1[i] = imax(n->x1[i], r.x1);
        n->y1[i] = imax(n->y1[i], r.y1);
        path[d] = ni;
        slot[d] = i;
        d++;
        ni = (uint32_t)n->ref[i];
        n = &t->nodes[ni];
    }
    if (n->count < MAXE) {
        node_set(n, n->count, r, ref);
        n->count++;
        return;
    }
    rect er = r;
    int32_t eref = ref;
    for (;;) {
        rect b1, b2;
        uint32_t nni = split_node(t, ni, er, eref, &b1, &b2);
        if (d == 0) {
            int lvl = t->nodes[ni].level + 1;
            uint32_t rt = node_alloc(t, lvl);
            node *R = &t->nodes[rt];
            node_set(R, 0, b1, (int32_t)ni);
            node_set(R, 1, b2, (int32_t)nni);
            R->count = 2;
            t->root = rt;
            return;
        }
        d--;
        node *p = &t->nodes[path[d]];
        node_set_rect(p, slot[d], b1);
        if (p->count < MAXE) {
            node_set(p, p->count, b2, (int32_t)nni);
            p->count++;
            return;
        }
        ni = path[d];
        er = b2;
        eref = (int32_t)nni;
    }
}

// --------------------------------------------------------------------- API

rtree *rtree_new(void) {
    rtree *t = xmalloc(sizeof *t);
    memset(t, 0, sizeof *t);
    t->free_head = NIL;
    t->root = node_alloc(t, 0);
    return t;
}

void rtree_free(rtree *t) {
    if (!t) return;
    free(t->nodes);
    free(t->hd);
    free(t->hn);
    free(t->rd);
    free(t->rid);
    free(t);
}

void rtree_insert(rtree *t, int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    rect r = {x0, y0, x1, y1};
    insert_at(t, r, id, 0);
    t->len++;
}

static int find_leaf(const rtree *t, uint32_t ni, rect r, int32_t id, uint32_t *pn, int *ps, int depth) {
    const node *n = &t->nodes[ni];
    pn[depth] = ni;
    if (n->level == 0) {
        uint32_t m = exact_mask(n, r, id);
        if (m) {
            ps[depth] = __builtin_ctz(m);
            return depth;
        }
        return -1;
    }
    uint32_t m = contain_mask(n, r);
    if (!m) return -1;
    for (uint32_t mm = m & (m - 1); mm; mm &= mm - 1) prefetch_node(&t->nodes[n->ref[__builtin_ctz(mm)]]);
    while (m) {
        int i = __builtin_ctz(m);
        m &= m - 1;
        ps[depth] = i;
        int res = find_leaf(t, (uint32_t)n->ref[i], r, id, pn, ps, depth + 1);
        if (res >= 0) return res;
    }
    return -1;
}

bool rtree_remove(rtree *t, int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    if (t->len == 0) return false;
    rect r = {x0, y0, x1, y1};
    uint32_t pn[MAXDEPTH];
    int ps[MAXDEPTH];
    int D = find_leaf(t, t->root, r, id, pn, ps, 0);
    if (D < 0) return false;
    node_remove_slot(&t->nodes[pn[D]], ps[D]);
    t->len--;

    // Condense the tree.
    rect rb_r[MAXDEPTH * MINE];
    int32_t rb_ref[MAXDEPTH * MINE];
    int rb_lvl[MAXDEPTH * MINE];
    int nrb = 0;
    for (int d = D; d > 0; d--) {
        node *n = &t->nodes[pn[d]];
        node *p = &t->nodes[pn[d - 1]];
        int s = ps[d - 1];
        if (n->count < MINE) {
            node_remove_slot(p, s);
            for (int i = 0; i < n->count; i++) {
                rb_r[nrb] = (rect){n->x0[i], n->y0[i], n->x1[i], n->y1[i]};
                rb_ref[nrb] = n->ref[i];
                rb_lvl[nrb] = n->level;
                nrb++;
            }
            node_free(t, pn[d]);
        } else {
            rect b = node_bbox(n);
            if (b.x0 == p->x0[s] && b.y0 == p->y0[s] && b.x1 == p->x1[s] && b.y1 == p->y1[s]) break;
            node_set_rect(p, s, b);
        }
    }
    // Reinsert set-aside entries (higher levels first).
    for (int i = nrb - 1; i >= 0; i--) insert_at(t, rb_r[i], rb_ref[i], rb_lvl[i]);

    // Shorten the tree.
    for (;;) {
        node *R = &t->nodes[t->root];
        if (R->level == 0 || R->count != 1) break;
        uint32_t old = t->root;
        t->root = (uint32_t)R->ref[0];
        node_free(t, old);
    }
    return true;
}

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 (t->len == 0) return 0;
    const node *nodes = t->nodes;
    uint64_t stack[MAXDEPTH * MAXE];
    int sp = 0;
    size_t total = 0, w = 0;
    stack[sp++] = ((uint64_t)(uint32_t)nodes[t->root].level << 32) | t->root;
    while (sp) {
        uint64_t e = stack[--sp];
        const node *n = &nodes[(uint32_t)e];
        uint32_t lvl = (uint32_t)(e >> 32);
        uint32_t m = isect_mask(n, x0, y0, x1, y1);
        if (lvl == 0) {
            total += (size_t)__builtin_popcount(m);
            if (w + MAXE <= cap) {
                while (m) {
                    out_ids[w++] = n->ref[__builtin_ctz(m)];
                    m &= m - 1;
                }
            } else {
                while (m && w < cap) {
                    out_ids[w++] = n->ref[__builtin_ctz(m)];
                    m &= m - 1;
                }
            }
        } else {
            uint64_t cl = (uint64_t)(lvl - 1) << 32;
            while (m) {
                uint32_t c = (uint32_t)n->ref[__builtin_ctz(m)];
                m &= m - 1;
                prefetch_node(&nodes[c]);
                stack[sp++] = cl | c;
            }
        }
    }
    return total;
}

// ------------------------------------------------------------------ nearest

static inline void dist16(const node *n, int32_t px, int32_t py, uint64_t *out) {
    for (int i = 0; i < MAXE; i++) {
        int32_t dx = imax(imax(n->x0[i] - px, px - n->x1[i]), 0);
        int32_t dy = imax(imax(n->y0[i] - py, py - n->y1[i]), 0);
        out[i] = (uint64_t)(uint32_t)dx * (uint32_t)dx + (uint64_t)(uint32_t)dy * (uint32_t)dy;
    }
}

size_t rtree_nearest(rtree *t, int32_t x, int32_t y, size_t k, int32_t *out_ids) {
    if (k == 0 || t->len == 0) return 0;
    if (k > t->len) k = t->len;
    if (t->rcap < k) {
        free(t->rd);
        free(t->rid);
        t->rcap = k < 64 ? 64 : k;
        t->rd = xmalloc(t->rcap * sizeof(uint64_t));
        t->rid = xmalloc(t->rcap * sizeof(int32_t));
    }
    if (t->hcap == 0) {
        t->hcap = 256;
        t->hd = xmalloc(t->hcap * sizeof(uint64_t));
        t->hn = xmalloc(t->hcap * sizeof(uint32_t));
    }
    uint64_t *rd = t->rd;
    int32_t *rid = t->rid;
    uint64_t *hd = t->hd;
    uint32_t *hn = t->hn;
    size_t hsz = 0, cnt = 0;
    const node *nodes = t->nodes;

    hd[0] = 0;
    hn[0] = t->root;
    hsz = 1;
    uint64_t dist[MAXE];

    while (hsz) {
        // pop min
        uint64_t d = hd[0];
        uint32_t ni = hn[0];
        if (cnt == k && d > rd[k - 1]) break;
        hsz--;
        if (hsz) {
            uint64_t ld = hd[hsz];
            uint32_t ln = hn[hsz];
            size_t i = 0;
            for (;;) {
                size_t c = 2 * i + 1;
                if (c >= hsz) break;
                if (c + 1 < hsz && hd[c + 1] < hd[c]) c++;
                if (hd[c] >= ld) break;
                hd[i] = hd[c];
                hn[i] = hn[c];
                i = c;
            }
            hd[i] = ld;
            hn[i] = ln;
        }

        const node *n = &nodes[ni];
        dist16(n, x, y, dist);
        int c = n->count;
        if (n->level == 0) {
            for (int i = 0; i < c; i++) {
                uint64_t e = dist[i];
                int32_t id = n->ref[i];
                size_t j;
                if (cnt < k) {
                    j = cnt++;
                } else if (e < rd[k - 1] || (e == rd[k - 1] && id < rid[k - 1])) {
                    j = k - 1;
                } else {
                    continue;
                }
                while (j > 0 && (rd[j - 1] > e || (rd[j - 1] == e && rid[j - 1] > id))) {
                    rd[j] = rd[j - 1];
                    rid[j] = rid[j - 1];
                    j--;
                }
                rd[j] = e;
                rid[j] = id;
            }
        } else {
            if (hsz + MAXE > t->hcap) {
                size_t nc = t->hcap * 2;
                uint64_t *a = realloc(t->hd, nc * sizeof(uint64_t));
                if (!a) abort();
                t->hd = hd = a;
                uint32_t *b = realloc(t->hn, nc * sizeof(uint32_t));
                if (!b) abort();
                t->hn = hn = b;
                t->hcap = nc;
            }
            for (int i = 0; i < c; i++) {
                uint64_t e = dist[i];
                if (cnt == k && e > rd[k - 1]) continue;
                uint32_t cn = (uint32_t)n->ref[i];
                prefetch_node(&nodes[cn]);
                // push
                size_t j = hsz++;
                while (j > 0) {
                    size_t p = (j - 1) >> 1;
                    if (hd[p] <= e) break;
                    hd[j] = hd[p];
                    hn[j] = hn[p];
                    j = p;
                }
                hd[j] = e;
                hn[j] = cn;
            }
        }
    }
    for (size_t i = 0; i < k; i++) out_ids[i] = rid[i];
    return k;
}

size_t rtree_len(const rtree *t) { return t->len; }

size_t rtree_height(const rtree *t) {
    if (t->len == 0) return 0;
    return (size_t)t->nodes[t->root].level + 1;
}

static size_t count_nodes(const rtree *t, uint32_t ni) {
    const node *n = &t->nodes[ni];
    size_t c = 1;
    if (n->level > 0)
        for (int i = 0; i < n->count; i++) c += count_nodes(t, (uint32_t)n->ref[i]);
    return c;
}

size_t rtree_node_count(const rtree *t) {
    if (t->len == 0) return 0;
    return count_nodes(t, t->root);
}
