/* Classic B-tree (CLRS ch. 18), minimum degree t = 16.
 *
 * Node layout: keys[32] (slot 31 and every slot >= n hold INT64_MAX as
 * padding), vals[31], n.  Leaves are 512 bytes; internal nodes append 32
 * child pointers (768 bytes).  Whether a node is a leaf is known from its
 * depth (all leaves are at depth height-1), so no flag is stored.
 *
 * In-node search counts keys < k over all 32 slots with portable vector
 * compares (the padding never compares less), giving the lower-bound index,
 * which is also the child index to descend into.
 */
#include "btree.h"

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

#define MAXK 31
#define MINK 15
#define MAXH 64
#define KPAD INT64_MAX

typedef struct node {
    int64_t keys[32];
    int64_t vals[31];
    int32_t n;
    int32_t pad_;
} __attribute__((aligned(128))) node;

typedef struct inode {
    node b;
    node *child[32];
} inode;

#define CH(x) (((inode *)(x))->child)

typedef struct pool {
    void *freelist;
    char *cur, *end;
    size_t nsize;
    size_t chunk_nodes;
} pool;

struct btree {
    node *root;
    size_t count;
    size_t height;
    pool pl, pi;
    void **chunks;
    size_t nchunks, capchunks;
};

typedef int64_t v2 __attribute__((vector_size(16)));

/* number of keys < k (0..31) */
static inline unsigned lb(const node *x, int64_t k) {
    const v2 *p = (const v2 *)x->keys;
    v2 kk = {k, k};
    v2 a0 = {0, 0}, a1 = {0, 0}, a2 = {0, 0}, a3 = {0, 0};
    for (int j = 0; j < 16; j += 4) {
        a0 += (v2)(p[j] < kk);
        a1 += (v2)(p[j + 1] < kk);
        a2 += (v2)(p[j + 2] < kk);
        a3 += (v2)(p[j + 3] < kk);
    }
    v2 s = (a0 + a1) + (a2 + a3);
    return (unsigned)(-(s[0] + s[1]));
}

/* number of keys <= k */
static inline unsigned le_count(const node *x, int64_t k) {
    const v2 *p = (const v2 *)x->keys;
    v2 kk = {k, k};
    v2 a0 = {0, 0}, a1 = {0, 0}, a2 = {0, 0}, a3 = {0, 0};
    for (int j = 0; j < 16; j += 4) {
        a0 += (v2)(p[j] <= kk);
        a1 += (v2)(p[j + 1] <= kk);
        a2 += (v2)(p[j + 2] <= kk);
        a3 += (v2)(p[j + 3] <= kk);
    }
    v2 s = (a0 + a1) + (a2 + a3);
    return (unsigned)(-(s[0] + s[1]));
}

/* ---------------------------------------------------------------- memory */

static __attribute__((noinline, cold)) void pool_grow(btree *t, pool *p) {
    size_t bytes = p->nsize * p->chunk_nodes;
    char *c = aligned_alloc(128, bytes);
    if (!c) abort();
    if (t->nchunks == t->capchunks) {
        size_t nc = t->capchunks ? t->capchunks * 2 : 16;
        void **a = realloc(t->chunks, nc * sizeof *a);
        if (!a) abort();
        t->chunks = a;
        t->capchunks = nc;
    }
    t->chunks[t->nchunks++] = c;
    p->cur = c;
    p->end = c + bytes;
    if (p->chunk_nodes < 4096) p->chunk_nodes *= 2;
}

static inline void *pool_alloc(btree *t, pool *p) {
    void *r = p->freelist;
    if (r) {
        p->freelist = *(void **)r;
        return r;
    }
    if (__builtin_expect(p->cur == p->end, 0)) pool_grow(t, p);
    r = p->cur;
    p->cur += p->nsize;
    return r;
}

static inline void pool_free(pool *p, void *x) {
    *(void **)x = p->freelist;
    p->freelist = x;
}

static inline void init_keys(node *x) {
    for (int j = 0; j < 32; j++) x->keys[j] = KPAD;
    x->n = 0;
}

static inline node *new_leaf(btree *t) {
    node *x = pool_alloc(t, &t->pl);
    init_keys(x);
    return x;
}

static inline node *new_inner(btree *t) {
    node *x = pool_alloc(t, &t->pi);
    init_keys(x);
    return x;
}

static inline void free_node(btree *t, node *x, bool leaf) {
    pool_free(leaf ? &t->pl : &t->pi, x);
}

btree *btree_new(void) {
    btree *t = calloc(1, sizeof *t);
    if (!t) abort();
    t->pl.nsize = sizeof(node);
    t->pl.chunk_nodes = 16;
    t->pi.nsize = sizeof(inode);
    t->pi.chunk_nodes = 16;
    return t;
}

void btree_free(btree *t) {
    if (!t) return;
    for (size_t i = 0; i < t->nchunks; i++) free(t->chunks[i]);
    free(t->chunks);
    free(t);
}

size_t btree_len(const btree *t) { return t->count; }
size_t btree_height(const btree *t) { return t->height; }

/* ------------------------------------------------------------------ get */

bool btree_get(const btree *t, int64_t k, int64_t *value) {
    const node *x = t->root;
    size_t h = t->height;
    if (!x) return false;
    for (;;) {
        unsigned i = lb(x, k);
        if (x->keys[i] == k && i < (unsigned)x->n) {
            *value = x->vals[i];
            return true;
        }
        if (--h == 0) return false;
        x = CH(x)[i];
    }
}

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

static inline void insert_at(node *x, unsigned i, int64_t k, int64_t v, node *right,
                             bool leaf) {
    unsigned n = (unsigned)x->n;
    unsigned m = n - i;
    memmove(x->keys + i + 1, x->keys + i, m * sizeof(int64_t));
    memmove(x->vals + i + 1, x->vals + i, m * sizeof(int64_t));
    x->keys[i] = k;
    x->vals[i] = v;
    if (!leaf) {
        node **c = CH(x);
        memmove(c + i + 2, c + i + 1, m * sizeof(node *));
        c[i + 1] = right;
    }
    x->n = (int32_t)(n + 1);
}

bool btree_insert(btree *t, int64_t k, int64_t v) {
    node *x = t->root;
    if (__builtin_expect(!x, 0)) {
        x = new_leaf(t);
        x->keys[0] = k;
        x->vals[0] = v;
        x->n = 1;
        t->root = x;
        t->height = 1;
        t->count = 1;
        return true;
    }
    node *path[MAXH];
    unsigned idx[MAXH];
    size_t h = t->height;
    size_t d = 0;
    for (;;) {
        unsigned i = lb(x, k);
        if (x->keys[i] == k && i < (unsigned)x->n) {
            x->vals[i] = v;
            return false;
        }
        path[d] = x;
        idx[d] = i;
        if (d + 1 == h) break;
        x = CH(x)[i];
        d++;
    }
    t->count++;

    node *right = NULL;
    bool leaf = true;
    for (;;) {
        x = path[d];
        unsigned i = idx[d];
        if (x->n < MAXK) {
            insert_at(x, i, k, v, right, leaf);
            return true;
        }
        /* split full node around keys[15]; then insert into the proper half */
        node *r = leaf ? new_leaf(t) : new_inner(t);
        memcpy(r->keys, x->keys + 16, 15 * sizeof(int64_t));
        memcpy(r->vals, x->vals + 16, 15 * sizeof(int64_t));
        if (!leaf) memcpy(CH(r), CH(x) + 16, 16 * sizeof(node *));
        int64_t mk = x->keys[15], mv = x->vals[15];
        for (int j = 15; j < 31; j++) x->keys[j] = KPAD;
        x->n = 15;
        r->n = 15;
        if (i <= 15)
            insert_at(x, i, k, v, right, leaf);
        else
            insert_at(r, i - 16, k, v, right, leaf);
        k = mk;
        v = mv;
        right = r;
        if (d == 0) {
            node *nr = new_inner(t);
            nr->keys[0] = k;
            nr->vals[0] = v;
            nr->n = 1;
            CH(nr)[0] = x;
            CH(nr)[1] = r;
            t->root = nr;
            t->height++;
            return true;
        }
        d--;
        leaf = false;
    }
}

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

/* x (child ci of p) underflowed; move s entries from left sibling l */
static void borrow_left(node *p, unsigned ci, node *l, node *x, bool leaf) {
    unsigned xn = (unsigned)x->n, ln = (unsigned)l->n;
    unsigned s = (ln - xn) / 2;
    memmove(x->keys + s, x->keys, xn * sizeof(int64_t));
    memmove(x->vals + s, x->vals, xn * sizeof(int64_t));
    x->keys[s - 1] = p->keys[ci - 1];
    x->vals[s - 1] = p->vals[ci - 1];
    memcpy(x->keys, l->keys + ln - s + 1, (s - 1) * sizeof(int64_t));
    memcpy(x->vals, l->vals + ln - s + 1, (s - 1) * sizeof(int64_t));
    p->keys[ci - 1] = l->keys[ln - s];
    p->vals[ci - 1] = l->vals[ln - s];
    if (!leaf) {
        memmove(CH(x) + s, CH(x), (xn + 1) * sizeof(node *));
        memcpy(CH(x), CH(l) + ln - s + 1, s * sizeof(node *));
    }
    for (unsigned j = ln - s; j < ln; j++) l->keys[j] = KPAD;
    l->n = (int32_t)(ln - s);
    x->n = (int32_t)(xn + s);
}

/* x (child ci of p) underflowed; move s entries from right sibling r */
static void borrow_right(node *p, unsigned ci, node *x, node *r, bool leaf) {
    unsigned xn = (unsigned)x->n, rn = (unsigned)r->n;
    unsigned s = (rn - xn) / 2;
    x->keys[xn] = p->keys[ci];
    x->vals[xn] = p->vals[ci];
    memcpy(x->keys + xn + 1, r->keys, (s - 1) * sizeof(int64_t));
    memcpy(x->vals + xn + 1, r->vals, (s - 1) * sizeof(int64_t));
    p->keys[ci] = r->keys[s - 1];
    p->vals[ci] = r->vals[s - 1];
    if (!leaf) {
        memcpy(CH(x) + xn + 1, CH(r), s * sizeof(node *));
        memmove(CH(r), CH(r) + s, (rn - s + 1) * sizeof(node *));
    }
    memmove(r->keys, r->keys + s, (rn - s) * sizeof(int64_t));
    memmove(r->vals, r->vals + s, (rn - s) * sizeof(int64_t));
    for (unsigned j = rn - s; j < rn; j++) r->keys[j] = KPAD;
    r->n = (int32_t)(rn - s);
    x->n = (int32_t)(xn + s);
}

/* merge r and separator p->keys[sep] into l; r is freed */
static void merge(btree *t, node *p, unsigned sep, node *l, node *r, bool leaf) {
    unsigned ln = (unsigned)l->n, rn = (unsigned)r->n;
    l->keys[ln] = p->keys[sep];
    l->vals[ln] = p->vals[sep];
    memcpy(l->keys + ln + 1, r->keys, rn * sizeof(int64_t));
    memcpy(l->vals + ln + 1, r->vals, rn * sizeof(int64_t));
    if (!leaf) memcpy(CH(l) + ln + 1, CH(r), (rn + 1) * sizeof(node *));
    l->n = (int32_t)(ln + 1 + rn);
    free_node(t, r, leaf);

    unsigned pn = (unsigned)p->n;
    unsigned m = pn - sep - 1;
    memmove(p->keys + sep, p->keys + sep + 1, m * sizeof(int64_t));
    memmove(p->vals + sep, p->vals + sep + 1, m * sizeof(int64_t));
    memmove(CH(p) + sep + 1, CH(p) + sep + 2, m * sizeof(node *));
    p->keys[pn - 1] = KPAD;
    p->n = (int32_t)(pn - 1);
}

bool btree_remove(btree *t, int64_t k) {
    node *x = t->root;
    if (!x) return false;
    node *path[MAXH];
    unsigned idx[MAXH];
    size_t h = t->height, d = 0;
    unsigned i;
    for (;;) {
        i = lb(x, k);
        path[d] = x;
        idx[d] = i;
        if (x->keys[i] == k && i < (unsigned)x->n) break;
        if (d + 1 == h) return false;
        x = CH(x)[i];
        d++;
    }
    t->count--;

    if (d + 1 < h) {
        /* internal node: replace with predecessor (max of left subtree) */
        node *y = CH(x)[i];
        size_t dd = d + 1;
        for (;;) {
            path[dd] = y;
            unsigned yn = (unsigned)y->n;
            if (dd + 1 == h) {
                idx[dd] = yn - 1;
                break;
            }
            idx[dd] = yn;
            y = CH(y)[yn];
            dd++;
        }
        unsigned yn = (unsigned)y->n - 1;
        x->keys[i] = y->keys[yn];
        x->vals[i] = y->vals[yn];
        y->keys[yn] = KPAD;
        y->n = (int32_t)yn;
        d = dd;
        x = y;
    } else {
        unsigned n = (unsigned)x->n;
        unsigned m = n - i - 1;
        memmove(x->keys + i, x->keys + i + 1, m * sizeof(int64_t));
        memmove(x->vals + i, x->vals + i + 1, m * sizeof(int64_t));
        x->keys[n - 1] = KPAD;
        x->n = (int32_t)(n - 1);
    }

    bool leaf = true;
    while (d > 0 && x->n < MINK) {
        node *p = path[d - 1];
        unsigned ci = idx[d - 1];
        if (ci > 0) {
            node *l = CH(p)[ci - 1];
            if (l->n > MINK) {
                borrow_left(p, ci, l, x, leaf);
                return true;
            }
        }
        if (ci < (unsigned)p->n) {
            node *r = CH(p)[ci + 1];
            if (r->n > MINK) {
                borrow_right(p, ci, x, r, leaf);
                return true;
            }
        }
        if (ci > 0)
            merge(t, p, ci - 1, CH(p)[ci - 1], x, leaf);
        else
            merge(t, p, ci, x, CH(p)[ci + 1], leaf);
        x = p;
        d--;
        leaf = false;
    }
    if (d == 0 && x->n == 0) {
        if (h == 1) {
            free_node(t, x, true);
            t->root = NULL;
            t->height = 0;
        } else {
            t->root = CH(x)[0];
            free_node(t, x, false);
            t->height = h - 1;
        }
    }
    return true;
}

/* ---------------------------------------------------------------- range */

size_t btree_range(const btree *t, int64_t lo, int64_t hi, int64_t *ok, int64_t *ov,
                   size_t limit) {
    const node *x = t->root;
    if (!x || lo > hi || limit == 0) return 0;
    const node *sn[MAXH];
    unsigned si[MAXH];
    size_t leafd = t->height - 1;
    size_t d = 0;
    size_t out = 0;
    unsigned i;

    for (;;) {
        i = lb(x, lo);
        if (d == leafd) break;
        sn[d] = x;
        si[d] = i;
        if (x->keys[i] == lo && i < (unsigned)x->n) goto emit_inner;
        x = CH(x)[i];
        d++;
    }

    for (;;) {
        /* leaf: x, starting at i */
        {
            unsigned n = (unsigned)x->n;
            if (i < n) {
                unsigned end = n;
                if (x->keys[n - 1] > hi) end = le_count(x, hi);
                if (end > i) {
                    size_t take = end - i;
                    size_t room = limit - out;
                    if (take > room) take = room;
                    memcpy(ok + out, x->keys + i, take * sizeof(int64_t));
                    memcpy(ov + out, x->vals + i, take * sizeof(int64_t));
                    out += take;
                    if (out == limit) return out;
                }
                if (end < n) return out;
            }
        }
        /* climb to the next ancestor with a pending key */
        for (;;) {
            if (d == 0) return out;
            d--;
            if (si[d] < (unsigned)sn[d]->n) break;
        }
    emit_inner: {
        const node *p = sn[d];
        unsigned pi = si[d];
        int64_t kk = p->keys[pi];
        if (kk > hi) return out;
        ok[out] = kk;
        ov[out] = p->vals[pi];
        if (++out == limit) return out;
        si[d] = pi + 1;
        x = CH(p)[pi + 1];
        d++;
        while (d < leafd) {
            sn[d] = x;
            si[d] = 0;
            x = CH(x)[0];
            d++;
        }
        i = 0;
    }
    }
}
