#include "btree.h"

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

#define BTREE_T        16u
#define BTREE_MIN_KEYS 15u  /* t - 1 */
#define BTREE_MAX_KEYS 31u  /* 2t - 1 */
#define BTREE_MAX_CH   32u  /* 2t */
#define BTREE_MAX_H    16u  /* 16^16 == 2^64 */
#define BTREE_NONE     UINT32_MAX

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

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

/*
 * Node layouts aligned to 128-byte Apple Silicon cache lines:
 *
 * LeafNode (512 bytes = 4 cache lines):
 *   Lines 0-1: keys[0..30], n, next_free   (256 bytes)
 *   Lines 2-3: vals[0..30], pad            (256 bytes)
 *
 * InternalNode (640 bytes = 5 cache lines):
 *   Lines 0-1: keys[0..30], n, next_free   (256 bytes)
 *   Line  2  : children[0..31]             (128 bytes)
 *   Lines 3-4: vals[0..30], pad            (256 bytes)
 *
 * Invariant: for every live node with `n` keys, keys[n..30] == INT64_MAX.
 * Since INT64_MAX < key is always false for any int64_t key, branchless
 * SIMD search over all 31 key slots yields the exact lower_bound in [0..n].
 */
typedef struct LeafNode {
    alignas(128) int64_t keys[BTREE_MAX_KEYS];
    uint32_t n;
    uint32_t next_free;
    int64_t  vals[BTREE_MAX_KEYS];
    uint64_t pad;
} LeafNode;

typedef struct InternalNode {
    alignas(128) int64_t keys[BTREE_MAX_KEYS];
    uint32_t n;
    uint32_t next_free;
    uint32_t children[BTREE_MAX_CH];
    int64_t  vals[BTREE_MAX_KEYS];
    uint64_t pad;
} InternalNode;

_Static_assert(sizeof(LeafNode) == 512, "LeafNode must be 512 bytes");
_Static_assert(offsetof(LeafNode, keys) == 0, "LeafNode.keys at 0");
_Static_assert(offsetof(LeafNode, n) == 248, "LeafNode.n at 248");
_Static_assert(offsetof(LeafNode, vals) == 256, "LeafNode.vals at 256");

_Static_assert(sizeof(InternalNode) == 640, "InternalNode must be 640 bytes");
_Static_assert(offsetof(InternalNode, keys) == 0, "InternalNode.keys at 0");
_Static_assert(offsetof(InternalNode, n) == 248, "InternalNode.n at 248");
_Static_assert(offsetof(InternalNode, children) == 256, "InternalNode.children at 256");
_Static_assert(offsetof(InternalNode, vals) == 384, "InternalNode.vals at 384");

struct btree {
    InternalNode *inodes;
    size_t        len;
    uint32_t      root;
    uint32_t      height;

    uint32_t      inode_used;
    uint32_t      inode_cap;
    uint32_t      inode_free;

    uint32_t      leaf_used;
    uint32_t      leaf_cap;
    uint32_t      leaf_free;

    /* Exponential leaf slabs indexed by clz(idx + 4): sizes 4, 8, 16, 32, ... */
    LeafNode     *leaf_slabs[32];
};

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

static inline void *xaligned_alloc(size_t align, size_t size) {
    void *p = aligned_alloc(align, size);
    if (UNLIKELY(!p)) abort();
    return p;
}

static inline LeafNode *leaf_at(btree *t, uint32_t idx) {
    uint32_t u = idx + 4u;
    unsigned lz = (unsigned)__builtin_clz(u);
    uint32_t off = u ^ (0x80000000u >> lz);
    return t->leaf_slabs[lz] + off;
}

static inline const LeafNode *leaf_at_const(const btree *t, uint32_t idx) {
    uint32_t u = idx + 4u;
    unsigned lz = (unsigned)__builtin_clz(u);
    uint32_t off = u ^ (0x80000000u >> lz);
    return t->leaf_slabs[lz] + off;
}

static uint32_t alloc_leaf_slow(btree *t) {
    uint32_t idx = t->leaf_used;
    uint32_t u = idx + 4u;
    unsigned lz = (unsigned)__builtin_clz(u);
    size_t count = (size_t)(0x80000000u >> lz);
    t->leaf_slabs[lz] = (LeafNode *)xaligned_alloc(128, count * sizeof(LeafNode));
    t->leaf_cap += (uint32_t)count;
    t->leaf_used = idx + 1u;
    return idx;
}

static inline uint32_t alloc_leaf(btree *t) {
    if (t->leaf_free != BTREE_NONE) {
        uint32_t idx = t->leaf_free;
        t->leaf_free = leaf_at(t, idx)->next_free;
        return idx;
    }
    if (LIKELY(t->leaf_used < t->leaf_cap)) {
        return t->leaf_used++;
    }
    return alloc_leaf_slow(t);
}

static inline void free_leaf(btree *t, uint32_t idx) {
    leaf_at(t, idx)->next_free = t->leaf_free;
    t->leaf_free = idx;
}

static uint32_t alloc_inode_slow(btree *t) {
    uint32_t new_cap = t->inode_cap ? t->inode_cap * 2u : 16u;
    InternalNode *p = (InternalNode *)xaligned_alloc(128, (size_t)new_cap * sizeof(InternalNode));
    if (t->inodes) {
        memcpy(p, t->inodes, (size_t)t->inode_used * sizeof(InternalNode));
        free(t->inodes);
    }
    t->inodes = p;
    t->inode_cap = new_cap;
    return t->inode_used++;
}

static inline uint32_t alloc_inode(btree *t) {
    if (t->inode_free != BTREE_NONE) {
        uint32_t idx = t->inode_free;
        t->inode_free = t->inodes[idx].next_free;
        return idx;
    }
    if (LIKELY(t->inode_used < t->inode_cap)) {
        return t->inode_used++;
    }
    return alloc_inode_slow(t);
}

static inline void free_inode(btree *t, uint32_t idx) {
    t->inodes[idx].next_free = t->inode_free;
    t->inode_free = idx;
}

static inline void fill_sentinel(int64_t *keys, uint32_t from) {
    for (uint32_t i = from; i < BTREE_MAX_KEYS; i++) {
        keys[i] = INT64_MAX;
    }
}

static inline v2i64 load_v2i64(const int64_t *p) {
    v2i64 v;
    memcpy(&v, p, sizeof(v));
    return v;
}

/*
 * Branchless portable-SIMD search across all 31 key slots.
 * Returns count of keys strictly less than `key`, which equals the
 * lower_bound position in [0..n] because keys[n..30] == INT64_MAX.
 */
static inline uint32_t search_keys(const int64_t *keys_ptr, int64_t key) {
    const int64_t *k = (const int64_t *)__builtin_assume_aligned(keys_ptr, 128);
    v2i64 vk = {key, key};

    v2i64 s0 = (load_v2i64(k +  0) < vk);
    v2i64 s1 = (load_v2i64(k +  2) < vk);
    v2i64 s2 = (load_v2i64(k +  4) < vk);
    v2i64 s3 = (load_v2i64(k +  6) < vk);

    s0 += (load_v2i64(k +  8) < vk);
    s1 += (load_v2i64(k + 10) < vk);
    s2 += (load_v2i64(k + 12) < vk);
    s3 += (load_v2i64(k + 14) < vk);

    s0 += (load_v2i64(k + 16) < vk);
    s1 += (load_v2i64(k + 18) < vk);
    s2 += (load_v2i64(k + 20) < vk);
    s3 += (load_v2i64(k + 22) < vk);

    s0 += (load_v2i64(k + 24) < vk);
    s1 += (load_v2i64(k + 26) < vk);
    s2 += (load_v2i64(k + 28) < vk);

    uint32_t last = (uint32_t)(k[30] < key);
    v2i64 s = (s0 + s1) + (s2 + s3);
    return (uint32_t)(-(s[0] + s[1])) + last;
}

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

btree *btree_new(void) {
    btree *t = (btree *)calloc(1, sizeof(btree));
    if (UNLIKELY(!t)) abort();
    t->root = BTREE_NONE;
    t->inode_free = BTREE_NONE;
    t->leaf_free = BTREE_NONE;
    return t;
}

void btree_free(btree *t) {
    if (!t) return;
    for (int i = 0; i < 32; i++) {
        free(t->leaf_slabs[i]);
    }
    free(t->inodes);
    free(t);
}

size_t btree_len(const btree *t) {
    return t->len;
}

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

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

bool btree_get(const btree *t, int64_t key, int64_t *value) {
    uint32_t h = t->height;
    if (UNLIKELY(h == 0)) return false;

    uint32_t idx = t->root;
    const InternalNode *inodes = t->inodes;

    for (uint32_t lvl = h - 1u; lvl > 0; lvl--) {
        const InternalNode *node = inodes + idx;
        __builtin_prefetch(node->children, 0, 3);
        uint32_t pos = search_keys(node->keys, key);
        if (UNLIKELY(pos < node->n && node->keys[pos] == key)) {
            *value = node->vals[pos];
            return true;
        }
        idx = node->children[pos];
    }

    const LeafNode *leaf = leaf_at_const(t, idx);
    __builtin_prefetch(leaf->vals, 0, 0);
    __builtin_prefetch(leaf->vals + 16, 0, 0);
    uint32_t pos = search_keys(leaf->keys, key);
    if (pos < leaf->n && leaf->keys[pos] == key) {
        *value = leaf->vals[pos];
        return true;
    }
    return false;
}

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

static void insert_split_and_climb(btree *t, LeafNode *leaf, uint32_t pos,
                                   int64_t key, int64_t value,
                                   const uint32_t *path_node,
                                   const uint8_t *path_pos) {
    /*
     * Split full leaf (31 old + 1 new = 32 entries):
     *   left  keeps 16 entries [0..15]
     *   prom  gets  entry 16
     *   right gets  15 entries [17..31]
     */
    uint32_t right_idx = alloc_leaf(t);
    LeafNode *right = leaf_at(t, right_idx);

    int64_t prom_k, prom_v;

    if (pos < 16u) {
        prom_k = leaf->keys[15];
        prom_v = leaf->vals[15];
        memcpy(right->keys, leaf->keys + 16, 15u * sizeof(int64_t));
        memcpy(right->vals, leaf->vals + 16, 15u * sizeof(int64_t));
        for (uint32_t i = 15u; i > pos; i--) {
            leaf->keys[i] = leaf->keys[i - 1u];
            leaf->vals[i] = leaf->vals[i - 1u];
        }
        leaf->keys[pos] = key;
        leaf->vals[pos] = value;
    } else if (pos == 16u) {
        prom_k = key;
        prom_v = value;
        memcpy(right->keys, leaf->keys + 16, 15u * sizeof(int64_t));
        memcpy(right->vals, leaf->vals + 16, 15u * sizeof(int64_t));
    } else {
        uint32_t rpos = pos - 17u;
        prom_k = leaf->keys[16];
        prom_v = leaf->vals[16];
        if (rpos > 0) {
            memcpy(right->keys, leaf->keys + 17, rpos * sizeof(int64_t));
            memcpy(right->vals, leaf->vals + 17, rpos * sizeof(int64_t));
        }
        right->keys[rpos] = key;
        right->vals[rpos] = value;
        uint32_t tail = 14u - rpos;
        if (tail > 0) {
            memcpy(right->keys + rpos + 1u, leaf->keys + pos, tail * sizeof(int64_t));
            memcpy(right->vals + rpos + 1u, leaf->vals + pos, tail * sizeof(int64_t));
        }
    }

    leaf->n = 16u;
    fill_sentinel(leaf->keys, 16u);
    right->n = 15u;
    fill_sentinel(right->keys, 15u);

    uint32_t prom_child = right_idx;

    /* Climb internal node path */
    for (int d = (int)t->height - 2; d >= 0; d--) {
        uint32_t p_idx = path_node[d];
        uint32_t p_pos = path_pos[d];
        InternalNode *p = t->inodes + p_idx;
        uint32_t pn = p->n;

        if (LIKELY(pn < BTREE_MAX_KEYS)) {
            for (uint32_t i = pn; i > p_pos; i--) {
                p->keys[i] = p->keys[i - 1u];
                p->vals[i] = p->vals[i - 1u];
                p->children[i + 1u] = p->children[i];
            }
            p->keys[p_pos] = prom_k;
            p->vals[p_pos] = prom_v;
            p->children[p_pos + 1u] = prom_child;
            p->n = pn + 1u;
            return;
        }

        /* Parent internal node is full (31 keys): split 16 + 1 + 15 */
        uint32_t pr_idx = alloc_inode(t);
        p = t->inodes + p_idx; /* re-fetch after potential reallocation */
        InternalNode *pr = t->inodes + pr_idx;

        int64_t next_k, next_v;

        if (p_pos < 16u) {
            next_k = p->keys[15];
            next_v = p->vals[15];
            memcpy(pr->keys, p->keys + 16, 15u * sizeof(int64_t));
            memcpy(pr->vals, p->vals + 16, 15u * sizeof(int64_t));
            memcpy(pr->children, p->children + 16, 16u * sizeof(uint32_t));

            for (uint32_t i = 15u; i > p_pos; i--) {
                p->keys[i] = p->keys[i - 1u];
                p->vals[i] = p->vals[i - 1u];
                p->children[i + 1u] = p->children[i];
            }
            p->keys[p_pos] = prom_k;
            p->vals[p_pos] = prom_v;
            p->children[p_pos + 1u] = prom_child;
        } else if (p_pos == 16u) {
            next_k = prom_k;
            next_v = prom_v;
            memcpy(pr->keys, p->keys + 16, 15u * sizeof(int64_t));
            memcpy(pr->vals, p->vals + 16, 15u * sizeof(int64_t));
            pr->children[0] = prom_child;
            memcpy(pr->children + 1, p->children + 17, 15u * sizeof(uint32_t));
        } else {
            uint32_t rpos = p_pos - 17u;
            next_k = p->keys[16];
            next_v = p->vals[16];
            if (rpos > 0) {
                memcpy(pr->keys, p->keys + 17, rpos * sizeof(int64_t));
                memcpy(pr->vals, p->vals + 17, rpos * sizeof(int64_t));
            }
            pr->keys[rpos] = prom_k;
            pr->vals[rpos] = prom_v;
            uint32_t tail = 14u - rpos;
            if (tail > 0) {
                memcpy(pr->keys + rpos + 1u, p->keys + p_pos, tail * sizeof(int64_t));
                memcpy(pr->vals + rpos + 1u, p->vals + p_pos, tail * sizeof(int64_t));
            }
            memcpy(pr->children, p->children + 17, (rpos + 1u) * sizeof(uint32_t));
            pr->children[rpos + 1u] = prom_child;
            if (tail > 0) {
                memcpy(pr->children + rpos + 2u, p->children + p_pos + 1u,
                       tail * sizeof(uint32_t));
            }
        }

        p->n = 16u;
        fill_sentinel(p->keys, 16u);
        pr->n = 15u;
        fill_sentinel(pr->keys, 15u);

        prom_k = next_k;
        prom_v = next_v;
        prom_child = pr_idx;
    }

    /* Root split: create a new internal root */
    uint32_t nr_idx = alloc_inode(t);
    InternalNode *nr = t->inodes + nr_idx;
    nr->keys[0] = prom_k;
    nr->vals[0] = prom_v;
    fill_sentinel(nr->keys, 1u);
    nr->n = 1u;
    nr->children[0] = t->root;
    nr->children[1] = prom_child;
    t->root = nr_idx;
    t->height++;
}

bool btree_insert(btree *t, int64_t key, int64_t value) {
    uint32_t h = t->height;
    if (UNLIKELY(h == 0)) {
        uint32_t r = alloc_leaf(t);
        LeafNode *leaf = leaf_at(t, r);
        leaf->keys[0] = key;
        leaf->vals[0] = value;
        fill_sentinel(leaf->keys, 1u);
        leaf->n = 1u;
        t->root = r;
        t->height = 1u;
        t->len = 1u;
        return true;
    }

    uint32_t path_node[BTREE_MAX_H];
    uint8_t  path_pos[BTREE_MAX_H];

    uint32_t idx = t->root;
    InternalNode *inodes = t->inodes;
    uint32_t depth = h - 1u;

    for (uint32_t d = 0; d < depth; d++) {
        InternalNode *node = inodes + idx;
        __builtin_prefetch(node->children, 0, 3);
        uint32_t n = node->n;
        uint32_t pos;
        if (key > node->keys[n - 1u]) {
            pos = n;
        } else {
            pos = search_keys(node->keys, key);
            if (UNLIKELY(pos < n && node->keys[pos] == key)) {
                node->vals[pos] = value;
                return false;
            }
        }
        path_node[d] = idx;
        path_pos[d] = (uint8_t)pos;
        idx = node->children[pos];
    }

    LeafNode *leaf = leaf_at(t, idx);
    __builtin_prefetch(leaf->vals, 1, 0);
    __builtin_prefetch(leaf->vals + 16, 1, 0);
    uint32_t n = leaf->n;
    uint32_t pos;
    if (key > leaf->keys[n - 1u]) {
        pos = n;
    } else {
        pos = search_keys(leaf->keys, key);
        if (UNLIKELY(pos < n && leaf->keys[pos] == key)) {
            leaf->vals[pos] = value;
            return false;
        }
    }

    t->len++;

    if (LIKELY(n < BTREE_MAX_KEYS)) {
        for (uint32_t i = n; i > pos; i--) {
            leaf->keys[i] = leaf->keys[i - 1u];
            leaf->vals[i] = leaf->vals[i - 1u];
        }
        leaf->keys[pos] = key;
        leaf->vals[pos] = value;
        leaf->n = n + 1u;
        return true;
    }

    insert_split_and_climb(t, leaf, pos, key, value, path_node, path_pos);
    return true;
}

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

static inline void remove_parent_entry(InternalNode *p, uint32_t sep_i) {
    uint32_t pn = p->n;
    for (uint32_t i = sep_i; i + 1u < pn; i++) {
        p->keys[i] = p->keys[i + 1u];
        p->vals[i] = p->vals[i + 1u];
        p->children[i + 1u] = p->children[i + 2u];
    }
    p->n = pn - 1u;
    p->keys[pn - 1u] = INT64_MAX;
}

static void rebalance_from_leaf(btree *t, uint32_t leaf_idx,
                                const uint32_t *path_node,
                                const uint8_t *path_pos) {
    uint32_t h = t->height;
    int d = (int)h - 2;

    InternalNode *p = t->inodes + path_node[d];
    uint32_t ci = path_pos[d];
    LeafNode *leaf = leaf_at(t, leaf_idx);

    /* Try balanced borrow from left leaf sibling */
    if (ci > 0) {
        LeafNode *left = leaf_at(t, p->children[ci - 1u]);
        uint32_t ln = left->n;
        if (ln > BTREE_MIN_KEYS) {
            uint32_t s = (ln - 14u) >> 1;
            for (uint32_t i = 14u; i-- > 0;) {
                leaf->keys[i + s] = leaf->keys[i];
                leaf->vals[i + s] = leaf->vals[i];
            }
            leaf->keys[s - 1u] = p->keys[ci - 1u];
            leaf->vals[s - 1u] = p->vals[ci - 1u];
            if (s > 1u) {
                memcpy(leaf->keys, left->keys + (ln - s + 1u), (s - 1u) * sizeof(int64_t));
                memcpy(leaf->vals, left->vals + (ln - s + 1u), (s - 1u) * sizeof(int64_t));
            }
            p->keys[ci - 1u] = left->keys[ln - s];
            p->vals[ci - 1u] = left->vals[ln - s];
            leaf->n = 14u + s;
            left->n = ln - s;
            fill_sentinel(left->keys, ln - s);
            return;
        }
    }

    /* Try balanced borrow from right leaf sibling */
    if (ci < p->n) {
        LeafNode *right = leaf_at(t, p->children[ci + 1u]);
        uint32_t rn = right->n;
        if (rn > BTREE_MIN_KEYS) {
            uint32_t s = (rn - 14u) >> 1;
            leaf->keys[14] = p->keys[ci];
            leaf->vals[14] = p->vals[ci];
            if (s > 1u) {
                memcpy(leaf->keys + 15, right->keys, (s - 1u) * sizeof(int64_t));
                memcpy(leaf->vals + 15, right->vals, (s - 1u) * sizeof(int64_t));
            }
            p->keys[ci] = right->keys[s - 1u];
            p->vals[ci] = right->vals[s - 1u];
            leaf->n = 14u + s;
            uint32_t rem = rn - s;
            memmove(right->keys, right->keys + s, rem * sizeof(int64_t));
            memmove(right->vals, right->vals + s, rem * sizeof(int64_t));
            right->n = rem;
            fill_sentinel(right->keys, rem);
            return;
        }
    }

    /* Merge leaf with a minimal (15-key) sibling -> 30-key leaf */
    if (ci > 0) {
        LeafNode *left = leaf_at(t, p->children[ci - 1u]);
        left->keys[15] = p->keys[ci - 1u];
        left->vals[15] = p->vals[ci - 1u];
        memcpy(left->keys + 16, leaf->keys, 14u * sizeof(int64_t));
        memcpy(left->vals + 16, leaf->vals, 14u * sizeof(int64_t));
        left->n = 30u;
        free_leaf(t, leaf_idx);
        remove_parent_entry(p, ci - 1u);
    } else {
        uint32_t right_idx = p->children[1];
        LeafNode *right = leaf_at(t, right_idx);
        leaf->keys[14] = p->keys[0];
        leaf->vals[14] = p->vals[0];
        memcpy(leaf->keys + 15, right->keys, 15u * sizeof(int64_t));
        memcpy(leaf->vals + 15, right->vals, 15u * sizeof(int64_t));
        leaf->n = 30u;
        free_leaf(t, right_idx);
        remove_parent_entry(p, 0u);
    }

    /* Rebalance internal nodes bottom-up */
    while (d > 0) {
        uint32_t curr_idx = path_node[d];
        InternalNode *curr = t->inodes + curr_idx;
        if (LIKELY(curr->n >= BTREE_MIN_KEYS)) return;

        d--;
        InternalNode *par = t->inodes + path_node[d];
        uint32_t pci = path_pos[d];

        /* Borrow from left internal sibling */
        if (pci > 0) {
            InternalNode *left = t->inodes + par->children[pci - 1u];
            uint32_t ln = left->n;
            if (ln > BTREE_MIN_KEYS) {
                uint32_t s = (ln - 14u) >> 1;
                for (uint32_t i = 14u; i-- > 0;) {
                    curr->keys[i + s] = curr->keys[i];
                    curr->vals[i + s] = curr->vals[i];
                }
                memmove(curr->children + s, curr->children, 15u * sizeof(uint32_t));
                curr->keys[s - 1u] = par->keys[pci - 1u];
                curr->vals[s - 1u] = par->vals[pci - 1u];
                if (s > 1u) {
                    memcpy(curr->keys, left->keys + (ln - s + 1u), (s - 1u) * sizeof(int64_t));
                    memcpy(curr->vals, left->vals + (ln - s + 1u), (s - 1u) * sizeof(int64_t));
                }
                memcpy(curr->children, left->children + (ln - s + 1u), s * sizeof(uint32_t));
                par->keys[pci - 1u] = left->keys[ln - s];
                par->vals[pci - 1u] = left->vals[ln - s];
                curr->n = 14u + s;
                left->n = ln - s;
                fill_sentinel(left->keys, ln - s);
                return;
            }
        }

        /* Borrow from right internal sibling */
        if (pci < par->n) {
            InternalNode *right = t->inodes + par->children[pci + 1u];
            uint32_t rn = right->n;
            if (rn > BTREE_MIN_KEYS) {
                uint32_t s = (rn - 14u) >> 1;
                curr->keys[14] = par->keys[pci];
                curr->vals[14] = par->vals[pci];
                if (s > 1u) {
                    memcpy(curr->keys + 15, right->keys, (s - 1u) * sizeof(int64_t));
                    memcpy(curr->vals + 15, right->vals, (s - 1u) * sizeof(int64_t));
                }
                memcpy(curr->children + 15, right->children, s * sizeof(uint32_t));
                par->keys[pci] = right->keys[s - 1u];
                par->vals[pci] = right->vals[s - 1u];
                curr->n = 14u + s;
                uint32_t rem = rn - s;
                memmove(right->keys, right->keys + s, rem * sizeof(int64_t));
                memmove(right->vals, right->vals + s, rem * sizeof(int64_t));
                memmove(right->children, right->children + s, (rem + 1u) * sizeof(uint32_t));
                right->n = rem;
                fill_sentinel(right->keys, rem);
                return;
            }
        }

        /* Merge internal node with a minimal (15-key) sibling */
        if (pci > 0) {
            InternalNode *left = t->inodes + par->children[pci - 1u];
            left->keys[15] = par->keys[pci - 1u];
            left->vals[15] = par->vals[pci - 1u];
            memcpy(left->keys + 16, curr->keys, 14u * sizeof(int64_t));
            memcpy(left->vals + 16, curr->vals, 14u * sizeof(int64_t));
            memcpy(left->children + 16, curr->children, 15u * sizeof(uint32_t));
            left->n = 30u;
            free_inode(t, curr_idx);
            remove_parent_entry(par, pci - 1u);
        } else {
            uint32_t right_idx = par->children[1];
            InternalNode *right = t->inodes + right_idx;
            curr->keys[14] = par->keys[0];
            curr->vals[14] = par->vals[0];
            memcpy(curr->keys + 15, right->keys, 15u * sizeof(int64_t));
            memcpy(curr->vals + 15, right->vals, 15u * sizeof(int64_t));
            memcpy(curr->children + 15, right->children, 16u * sizeof(uint32_t));
            curr->n = 30u;
            free_inode(t, right_idx);
            remove_parent_entry(par, 0u);
        }
    }

    /* Check if the internal root became empty */
    uint32_t root_idx = path_node[0];
    InternalNode *root = t->inodes + root_idx;
    if (UNLIKELY(root->n == 0)) {
        t->root = root->children[0];
        free_inode(t, root_idx);
        t->height--;
    }
}

bool btree_remove(btree *t, int64_t key) {
    uint32_t h = t->height;
    if (UNLIKELY(h == 0)) return false;

    uint32_t path_node[BTREE_MAX_H];
    uint8_t  path_pos[BTREE_MAX_H];

    uint32_t idx = t->root;
    InternalNode *inodes = t->inodes;
    uint32_t depth = h - 1u;

    for (uint32_t d = 0; d < depth; d++) {
        InternalNode *node = inodes + idx;
        __builtin_prefetch(node->children, 0, 3);
        uint32_t pos;
        if (key <= node->keys[0]) {
            pos = 0u;
            if (LIKELY(key < node->keys[0])) {
                path_node[d] = idx;
                path_pos[d] = 0u;
                idx = node->children[0];
                continue;
            }
        } else {
            pos = search_keys(node->keys, key);
            if (LIKELY(pos >= node->n || node->keys[pos] != key)) {
                path_node[d] = idx;
                path_pos[d] = (uint8_t)pos;
                idx = node->children[pos];
                continue;
            }
        }

        /* Found key in internal node at `pos`: swap with in-order predecessor */
        path_node[d] = idx;
        path_pos[d] = (uint8_t)pos;
        uint32_t cur = node->children[pos];
        for (uint32_t sub = d + 1u; sub < depth; sub++) {
            InternalNode *cn = inodes + cur;
            uint32_t last_ch = cn->n;
            path_node[sub] = cur;
            path_pos[sub] = (uint8_t)last_ch;
            cur = cn->children[last_ch];
        }

        LeafNode *pred_leaf = leaf_at(t, cur);
        uint32_t last = pred_leaf->n - 1u;
        node->keys[pos] = pred_leaf->keys[last];
        node->vals[pos] = pred_leaf->vals[last];
        pred_leaf->n = last;
        pred_leaf->keys[last] = INT64_MAX;
        t->len--;

        if (UNLIKELY(last < BTREE_MIN_KEYS)) {
            rebalance_from_leaf(t, cur, path_node, path_pos);
        }
        return true;
    }

    LeafNode *leaf = leaf_at(t, idx);
    __builtin_prefetch(leaf->vals, 1, 0);
    __builtin_prefetch(leaf->vals + 16, 1, 0);
    uint32_t n = leaf->n;
    uint32_t pos;
    if (key <= leaf->keys[0]) {
        if (key < leaf->keys[0]) return false;
        pos = 0u;
    } else {
        pos = search_keys(leaf->keys, key);
        if (pos >= n || leaf->keys[pos] != key) return false;
    }

    for (uint32_t i = pos; i + 1u < n; i++) {
        leaf->keys[i] = leaf->keys[i + 1u];
        leaf->vals[i] = leaf->vals[i + 1u];
    }
    uint32_t new_n = n - 1u;
    leaf->n = new_n;
    leaf->keys[new_n] = INT64_MAX;
    t->len--;

    if (UNLIKELY(h == 1u)) {
        if (new_n == 0) {
            free_leaf(t, idx);
            t->root = BTREE_NONE;
            t->height = 0;
        }
        return true;
    }

    if (UNLIKELY(new_n < BTREE_MIN_KEYS)) {
        rebalance_from_leaf(t, idx, path_node, path_pos);
    }
    return true;
}

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

static inline void prefetch_leaf(const btree *t, uint32_t leaf_idx) {
    const char *p = (const char *)leaf_at_const(t, leaf_idx);
    __builtin_prefetch(p,       0, 0);
    __builtin_prefetch(p + 128, 0, 0);
    __builtin_prefetch(p + 256, 0, 0);
    __builtin_prefetch(p + 384, 0, 0);
}

/*
 * Emit entries from a leaf whose keys are all guaranteed >= lo.
 * Returns true if traversal must stop (hit hi or limit).
 */
static inline bool emit_leaf(const btree *t, uint32_t leaf_idx, int64_t hi,
                             int64_t *out_keys, int64_t *out_vals,
                             size_t *out_p, size_t limit) {
    const LeafNode *leaf = leaf_at_const(t, leaf_idx);
    uint32_t n = leaf->n;
    size_t out = *out_p;
    size_t rem = limit - out;

    if (LIKELY(leaf->keys[n - 1u] <= hi && (size_t)n <= rem)) {
        memcpy(out_keys + out, leaf->keys, (size_t)n * sizeof(int64_t));
        memcpy(out_vals + out, leaf->vals, (size_t)n * sizeof(int64_t));
        out += n;
        *out_p = out;
        return out == limit;
    }

    for (uint32_t i = 0; i < n; i++) {
        int64_t k = leaf->keys[i];
        if (k > hi) {
            *out_p = out;
            return true;
        }
        out_keys[out] = k;
        out_vals[out] = leaf->vals[i];
        out++;
        if (out == limit) {
            *out_p = out;
            return true;
        }
    }
    *out_p = out;
    return false;
}

/*
 * Emit entries from a level-1 internal node (whose children are leaves)
 * whose keys are all guaranteed >= lo, prefetching upcoming leaves ahead.
 */
static bool emit_level1(const btree *t, uint32_t node_idx, int64_t hi,
                        int64_t *out_keys, int64_t *out_vals,
                        size_t *out_p, size_t limit) {
    const InternalNode *node = t->inodes + node_idx;
    uint32_t n = node->n;
    const uint32_t *ch = node->children;
    const int64_t *keys = node->keys;
    const int64_t *vals = node->vals;

    /* Initial prefetch of upcoming leaves (4 leaves in flight) */
    size_t rem = limit - *out_p;
    if (rem > 16u && keys[0] <= hi) prefetch_leaf(t, ch[1]);
    if (n >= 2u && rem > 32u && keys[1] <= hi) prefetch_leaf(t, ch[2]);
    if (n >= 3u && rem > 48u && keys[2] <= hi) prefetch_leaf(t, ch[3]);
    if (n >= 4u && rem > 64u && keys[3] <= hi) prefetch_leaf(t, ch[4]);

    for (uint32_t i = 0; ; i++) {
        rem = limit - *out_p;
        if (i + 4u <= n && rem > 64u && keys[i + 3u] <= hi) {
            prefetch_leaf(t, ch[i + 4u]);
        }

        if (emit_leaf(t, ch[i], hi, out_keys, out_vals, out_p, limit)) {
            return true;
        }
        if (i == n) return false;

        int64_t k = keys[i];
        if (k > hi) return true;
        size_t out = *out_p;
        out_keys[out] = k;
        out_vals[out] = vals[i];
        out++;
        *out_p = out;
        if (out == limit) return true;
    }
}

/*
 * Emit entries from a subtree rooted at internal node `node_idx` at `lvl >= 1`
 * whose keys are all guaranteed >= lo.
 */
static bool emit_subtree(const btree *t, uint32_t node_idx, uint32_t lvl,
                         int64_t hi, int64_t *out_keys, int64_t *out_vals,
                         size_t *out_p, size_t limit) {
    if (lvl == 1u) {
        return emit_level1(t, node_idx, hi, out_keys, out_vals, out_p, limit);
    }

    const InternalNode *node = t->inodes + node_idx;
    uint32_t n = node->n;
    for (uint32_t i = 0; ; i++) {
        if (emit_subtree(t, node->children[i], lvl - 1u, hi,
                         out_keys, out_vals, out_p, limit)) {
            return true;
        }
        if (i == n) return false;

        int64_t k = node->keys[i];
        if (k > hi) return true;
        size_t out = *out_p;
        out_keys[out] = k;
        out_vals[out] = node->vals[i];
        out++;
        *out_p = out;
        if (out == limit) return true;
    }
}

size_t btree_range(const btree *t, int64_t lo, int64_t hi,
                   int64_t *out_keys, int64_t *out_vals, size_t limit) {
    uint32_t h = t->height;
    if (UNLIKELY(h == 0 || limit == 0 || lo > hi)) return 0;

    uint32_t stack_node[BTREE_MAX_H];
    uint8_t  stack_pos[BTREE_MAX_H];

    uint32_t idx = t->root;
    const InternalNode *inodes = t->inodes;
    size_t out = 0;
    uint32_t resume_lvl = 1u;

    /* Phase 1: Seek down to `lo` */
    for (uint32_t lvl = h - 1u; lvl > 0; lvl--) {
        const InternalNode *node = inodes + idx;
        __builtin_prefetch(node->children, 0, 3);
        uint32_t pos = search_keys(node->keys, lo);
        stack_node[lvl] = idx;
        stack_pos[lvl] = (uint8_t)pos;

        if (UNLIKELY(pos < node->n && node->keys[pos] == lo)) {
            /* Exact match in internal node: skip left subtree, start Phase 2 here */
            resume_lvl = lvl;
            goto phase2;
        }
        idx = node->children[pos];
    }

    /* Emit matching entries from the starting leaf */
    {
        const LeafNode *leaf = leaf_at_const(t, idx);
        __builtin_prefetch(leaf->vals, 0, 0);
        __builtin_prefetch(leaf->vals + 16, 0, 0);
        uint32_t n = leaf->n;
        uint32_t pos = search_keys(leaf->keys, lo);
        if (pos < n) {
            uint32_t avail = n - pos;
            if (leaf->keys[n - 1u] <= hi && (size_t)avail <= limit) {
                memcpy(out_keys, leaf->keys + pos, (size_t)avail * sizeof(int64_t));
                memcpy(out_vals, leaf->vals + pos, (size_t)avail * sizeof(int64_t));
                out = avail;
                if (out == limit) return out;
            } else {
                for (uint32_t i = pos; i < n; i++) {
                    int64_t k = leaf->keys[i];
                    if (k > hi) return out;
                    out_keys[out] = k;
                    out_vals[out] = leaf->vals[i];
                    out++;
                    if (out == limit) return out;
                }
            }
        }
    }

    if (h == 1u) return out;

phase2:
    /* Phase 2: Resume ascending in-order walk up the saved path */
    for (uint32_t lvl = resume_lvl; lvl < h; lvl++) {
        const InternalNode *node = inodes + stack_node[lvl];
        uint32_t n = node->n;
        uint32_t pos = stack_pos[lvl];

        if (lvl == 1u) {
            const uint32_t *ch = node->children;
            const int64_t *keys = node->keys;
            const int64_t *vals = node->vals;
            size_t rem = limit - out;
            if (pos < n && keys[pos] <= hi && rem > 1u) prefetch_leaf(t, ch[pos + 1u]);
            if (pos + 1u < n && keys[pos + 1u] <= hi && rem > 17u) prefetch_leaf(t, ch[pos + 2u]);
            if (pos + 2u < n && keys[pos + 2u] <= hi && rem > 33u) prefetch_leaf(t, ch[pos + 3u]);
            if (pos + 3u < n && keys[pos + 3u] <= hi && rem > 49u) prefetch_leaf(t, ch[pos + 4u]);

            while (pos < n) {
                int64_t k = keys[pos];
                if (k > hi) return out;
                out_keys[out] = k;
                out_vals[out] = vals[pos];
                out++;
                if (out == limit) return out;

                pos++;
                rem = limit - out;
                if (pos + 4u <= n && rem > 64u && keys[pos + 3u] <= hi) {
                    prefetch_leaf(t, ch[pos + 4u]);
                }
                if (emit_leaf(t, ch[pos], hi, out_keys, out_vals, &out, limit)) {
                    return out;
                }
            }
        } else {
            while (pos < n) {
                int64_t k = node->keys[pos];
                if (k > hi) return out;
                out_keys[out] = k;
                out_vals[out] = node->vals[pos];
                out++;
                if (out == limit) return out;

                pos++;
                if (emit_subtree(t, node->children[pos], lvl - 1u, hi,
                                 out_keys, out_vals, &out, limit)) {
                    return out;
                }
            }
        }
    }

    return out;
}
