#include "rbtree.h"

#include <stdlib.h>

/*
 * High-performance Red-Black Tree (CLRS / Guibas-Sedgewick)
 *
 * Design highlights:
 * - Split hot/cold storage:
 *     RBNode is 16 bytes: { int64_t key; uint32_t ch[2]; }.
 *     8 hot nodes fit in a single 128-byte cache line with zero splits.
 *     Values live in a parallel int64_t *vals array, untouched by get-miss,
 *     search descents, and deletions (delete swaps links rather than copying
 *     key/value payloads).
 * - 32-bit pool indices (0 = NIL sentinel, 1..2^31-1 = live nodes):
 *     Contiguous realloc-grown pool with an intrusive LIFO freelist.
 * - Parentless (L1 stack-based) bottom-up rebalancing:
 *     No parent pointers in nodes; max RB height <= 2*log2(N+1) <= 62.
 * - Color stored in bit 31 of the parent's incoming child link (Guibas-Sedgewick):
 *     Bit 31 = 1 => RED, 0 => BLACK (root is always BLACK).
 *     Eliminates cold DRAM loads of uncles during insert fixup and nephews
 *     during delete fixup (Cases 2 and 4 never load any nephew node).
 */

#define RED_BIT  0x80000000u
#define IDX_MASK 0x7FFFFFFFu

#define INITIAL_CAP 64u

typedef struct {
    int64_t  key;
    uint32_t ch[2]; /* ch[0] = left, ch[1] = right; bit 31 = color of child */
} RBNode;

struct rbtree {
    RBNode  *nodes;
    int64_t *vals;
    uint32_t root;      /* always BLACK (bit 31 == 0); 0 when empty */
    uint32_t len;
    uint32_t cap;
    uint32_t bump;      /* next fresh index (starts at 1; 0 is NIL) */
    uint32_t free_head; /* intrusive LIFO freelist head (0 = empty) */
};

static __attribute__((noinline)) void rbtree_grow(rbtree *t) {
    uint32_t old_cap = t->cap;
    uint32_t new_cap;
    if (old_cap >= (IDX_MASK >> 1)) {
        if (old_cap >= IDX_MASK) abort();
        new_cap = IDX_MASK;
    } else {
        new_cap = old_cap * 2u;
    }

    RBNode *new_nodes = realloc(t->nodes, (size_t)new_cap * sizeof(RBNode));
    if (!new_nodes) abort();
    t->nodes = new_nodes;

    int64_t *new_vals = realloc(t->vals, (size_t)new_cap * sizeof(int64_t));
    if (!new_vals) abort();
    t->vals = new_vals;

    t->cap = new_cap;
}

static inline uint32_t alloc_node(rbtree *t) {
    uint32_t fh = t->free_head;
    if (fh != 0) {
        t->free_head = t->nodes[fh].ch[0];
        return fh;
    }
    uint32_t b = t->bump;
    if (__builtin_expect(b == t->cap, 0)) {
        rbtree_grow(t);
    }
    t->bump = b + 1u;
    return b;
}

rbtree *rbtree_new(void) {
    rbtree *t = malloc(sizeof(rbtree));
    if (!t) abort();

    t->nodes = malloc((size_t)INITIAL_CAP * sizeof(RBNode));
    t->vals  = malloc((size_t)INITIAL_CAP * sizeof(int64_t));
    if (!t->nodes || !t->vals) abort();

    /* Initialize NIL sentinel at index 0 */
    t->nodes[0].key   = 0;
    t->nodes[0].ch[0] = 0;
    t->nodes[0].ch[1] = 0;
    t->vals[0]        = 0;

    t->root      = 0;
    t->len       = 0;
    t->cap       = INITIAL_CAP;
    t->bump      = 1u;
    t->free_head = 0;
    return t;
}

void rbtree_free(rbtree *t) {
    if (!t) return;
    free(t->nodes);
    free(t->vals);
    free(t);
}

bool rbtree_get(const rbtree *t, int64_t key, int64_t *value) {
    const RBNode * restrict nodes = t->nodes;
    uint32_t x = t->root;
    while (x != 0) {
        const RBNode *n = &nodes[x];
        int64_t k = n->key;
        uint32_t l = n->ch[0] & IDX_MASK;
        uint32_t r = n->ch[1] & IDX_MASK;
        if (__builtin_expect(key == k, 0)) {
            *value = t->vals[x];
            return true;
        }
        x = (key < k) ? l : r;
    }
    return false;
}

bool rbtree_insert(rbtree *t, int64_t key, int64_t value) {
    uint32_t path[64];
    uint8_t  dirs[64];
    uint32_t sp = 0;

    RBNode *nodes = t->nodes;
    uint32_t x = t->root;
    while (x != 0) {
        const RBNode *n = &nodes[x];
        int64_t k = n->key;
        uint32_t l = n->ch[0] & IDX_MASK;
        uint32_t r = n->ch[1] & IDX_MASK;
        if (__builtin_expect(key == k, 0)) {
            t->vals[x] = value;
            return false;
        }
        uint8_t d = (uint8_t)(key > k);
        path[sp] = x;
        dirs[sp] = d;
        sp++;
        x = d ? r : l;
    }

    uint32_t z = alloc_node(t);
    nodes = t->nodes; /* reload in case rbtree_grow reallocated */
    nodes[z].key   = key;
    nodes[z].ch[0] = 0;
    nodes[z].ch[1] = 0;
    t->vals[z]     = value;
    t->len++;

    if (__builtin_expect(sp == 0, 0)) {
        t->root = z; /* root is BLACK */
        return true;
    }

    /* Attach z as a RED leaf under path[sp - 1] */
    nodes[path[sp - 1]].ch[dirs[sp - 1]] = z | RED_BIT;

    /* Bottom-up insert fixup */
    while (sp >= 2u) {
        uint32_t p  = path[sp - 1];
        uint32_t g  = path[sp - 2];
        uint8_t  gd = dirs[sp - 2];

        uint32_t p_link = nodes[g].ch[gd];
        if ((p_link & RED_BIT) == 0) {
            return true; /* parent is BLACK: done */
        }

        /* Parent p is RED, so grandparent g is BLACK. Check uncle color in g! */
        uint32_t u_link = nodes[g].ch[gd ^ 1u];
        if (u_link & RED_BIT) {
            /* Case 1: Uncle is RED -> recolor p and u BLACK, g RED */
            nodes[g].ch[gd]      = p_link & IDX_MASK;
            nodes[g].ch[gd ^ 1u] = u_link & IDX_MASK;
            sp -= 2u;
            if (sp == 0) {
                return true; /* g is root: stays BLACK */
            }
            nodes[path[sp - 1]].ch[dirs[sp - 1]] |= RED_BIT;
            continue;
        }

        /* Uncle is BLACK -> 1 or 2 rotations and terminate */
        uint32_t *gg_link = (sp == 2u)
            ? &t->root
            : &nodes[path[sp - 3]].ch[dirs[sp - 3]];
        uint8_t pd = dirs[sp - 1];

        if (pd == gd) {
            /* Case 3 (zig-zig): single rotation at g */
            nodes[g].ch[gd]      = nodes[p].ch[gd ^ 1u];
            nodes[p].ch[gd ^ 1u] = g | RED_BIT;
            *gg_link             = p; /* p becomes BLACK */
        } else {
            /* Case 2 + 3 (zig-zag): fused double rotation */
            uint32_t child = nodes[p].ch[pd] & IDX_MASK;
            nodes[p].ch[pd]      = nodes[child].ch[gd];
            nodes[g].ch[gd]      = nodes[child].ch[pd];
            nodes[child].ch[gd]  = p | RED_BIT;
            nodes[child].ch[pd]  = g | RED_BIT;
            *gg_link             = child; /* child becomes BLACK */
        }
        return true;
    }

    return true;
}

bool rbtree_remove(rbtree *t, int64_t key) {
    uint32_t path[64];
    uint8_t  dirs[64];
    uint32_t sp = 0;

    RBNode * restrict nodes = t->nodes;
    uint32_t x = t->root;
    while (x != 0) {
        const RBNode *n = &nodes[x];
        int64_t k = n->key;
        uint32_t l = n->ch[0] & IDX_MASK;
        uint32_t r = n->ch[1] & IDX_MASK;
        if (__builtin_expect(key == k, 0)) {
            break;
        }
        uint8_t d = (uint8_t)(key > k);
        path[sp] = x;
        dirs[sp] = d;
        sp++;
        x = d ? r : l;
    }
    if (x == 0) return false;

    uint32_t x_left_link  = nodes[x].ch[0];
    uint32_t x_right_link = nodes[x].ch[1];
    uint32_t x_left       = x_left_link  & IDX_MASK;
    uint32_t x_right      = x_right_link & IDX_MASK;
    uint32_t *x_link_ptr  = (sp == 0)
        ? &t->root
        : &nodes[path[sp - 1]].ch[dirs[sp - 1]];

    bool need_fixup = false;

    if (x_left == 0 || x_right == 0) {
        uint32_t child_link = (x_left != 0) ? x_left_link : x_right_link;
        if (*x_link_ptr & RED_BIT) {
            *x_link_ptr = child_link; /* RED node with <=1 child has 0 children */
        } else if (child_link & RED_BIT) {
            *x_link_ptr = child_link & IDX_MASK; /* recolor sole RED child BLACK */
        } else {
            *x_link_ptr = child_link; /* 0; BLACK leaf removed */
            need_fixup = true;
        }
    } else {
        /* Two children: splice in-order successor s into x's position without touching vals[] */
        uint32_t x_pos = sp;
        dirs[sp] = 1u;
        sp++;

        uint32_t s = x_right;
        uint32_t s_left = nodes[s].ch[0] & IDX_MASK;
        while (s_left != 0) {
            path[sp] = s;
            dirs[sp] = 0u;
            sp++;
            s = s_left;
            s_left = nodes[s].ch[0] & IDX_MASK;
        }

        uint32_t s_right_link = nodes[s].ch[1];
        uint32_t x_color = *x_link_ptr & RED_BIT;
        *x_link_ptr = s | x_color;
        path[x_pos] = s;
        nodes[s].ch[0] = x_left_link;

        if (sp == x_pos + 1u) {
            /* s was the direct right child of x */
            if ((x_right_link & RED_BIT) == 0) {
                if (s_right_link & RED_BIT) {
                    nodes[s].ch[1] = s_right_link & IDX_MASK;
                } else {
                    need_fixup = true;
                }
            }
        } else {
            /* s was the left child of path[sp - 1] */
            uint32_t s_parent = path[sp - 1];
            uint32_t s_old_link = nodes[s_parent].ch[0];
            nodes[s].ch[1] = x_right_link;
            if (s_old_link & RED_BIT) {
                nodes[s_parent].ch[0] = s_right_link;
            } else if (s_right_link & RED_BIT) {
                nodes[s_parent].ch[0] = s_right_link & IDX_MASK;
            } else {
                nodes[s_parent].ch[0] = s_right_link;
                need_fixup = true;
            }
        }
    }

    /* Recycle node x */
    t->len--;
    if (__builtin_expect(t->len == 0, 0)) {
        t->bump      = 1u;
        t->free_head = 0;
        return true;
    }
    nodes[x].ch[0] = t->free_head;
    t->free_head   = x;

    if (!need_fixup) return true;

    /* Bottom-up delete fixup */
    while (sp > 0) {
        uint32_t p = path[sp - 1];
        uint8_t  d = dirs[sp - 1];
        uint32_t *p_link_ptr = (sp == 1u)
            ? &t->root
            : &nodes[path[sp - 2]].ch[dirs[sp - 2]];
        uint32_t w_link = nodes[p].ch[d ^ 1u];

        if (w_link & RED_BIT) {
            /* Case 1: Sibling w is RED -> rotate p, w becomes BLACK, p becomes RED */
            uint32_t w = w_link & IDX_MASK;
            uint32_t new_w_link = nodes[w].ch[d];
            nodes[p].ch[d ^ 1u] = new_w_link;
            nodes[w].ch[d]      = p | RED_BIT;
            *p_link_ptr         = w;
            p_link_ptr          = &nodes[w].ch[d];
            w_link              = new_w_link;
        }

        /* Now sibling w is BLACK */
        uint32_t w         = w_link;
        uint32_t near_link = nodes[w].ch[d];
        uint32_t far_link  = nodes[w].ch[d ^ 1u];

        if (((near_link | far_link) & RED_BIT) == 0) {
            /* Case 2: Both nephews are BLACK -> recolor w RED */
            nodes[p].ch[d ^ 1u] = w | RED_BIT;
            if (*p_link_ptr & RED_BIT) {
                *p_link_ptr &= IDX_MASK; /* p was RED -> recolor BLACK, done */
                return true;
            }
            sp--;
            continue;
        }

        uint32_t p_color = *p_link_ptr & RED_BIT;
        if ((far_link & RED_BIT) == 0) {
            /* Case 3 + 4 fused: near nephew is RED, far nephew is BLACK */
            uint32_t near = near_link & IDX_MASK;
            nodes[p].ch[d ^ 1u]    = nodes[near].ch[d];
            nodes[w].ch[d]         = nodes[near].ch[d ^ 1u];
            nodes[near].ch[d]      = p;
            nodes[near].ch[d ^ 1u] = w;
            *p_link_ptr            = near | p_color;
        } else {
            /* Case 4: far nephew is RED */
            nodes[p].ch[d ^ 1u] = near_link;
            nodes[w].ch[d]      = p;
            nodes[w].ch[d ^ 1u] = far_link & IDX_MASK;
            *p_link_ptr         = w | p_color;
        }
        return true;
    }

    return true;
}

size_t rbtree_range(const rbtree *t, int64_t lo, int64_t hi,
                    int64_t * restrict out_keys, int64_t * restrict out_vals,
                    size_t limit) {
    if (limit == 0 || lo > hi || t->root == 0) return 0;

    const RBNode * restrict nodes = t->nodes;
    const int64_t * restrict vals = t->vals;
    uint32_t stack[64];
    uint32_t sp = 0;

    /* Phase 1: Branchless descent to the split node (first node in [lo, hi]) */
    uint32_t x = t->root;
    while (x != 0) {
        const RBNode *n = &nodes[x];
        int64_t k = n->key;
        uint32_t l = n->ch[0] & IDX_MASK;
        uint32_t r = n->ch[1] & IDX_MASK;
        if (__builtin_expect(k >= lo && k <= hi, 0)) {
            break;
        }
        x = (k < lo) ? r : l;
    }
    if (x == 0) return 0;

    /* Phase 2: Descend split node's left subtree to lo; every key here is < hi */
    stack[sp++] = x;
    if (nodes[x].key > lo) {
        uint32_t cur = nodes[x].ch[0] & IDX_MASK;
        while (cur != 0) {
            const RBNode *n = &nodes[cur];
            int64_t k = n->key;
            uint32_t l = n->ch[0] & IDX_MASK;
            uint32_t r = n->ch[1] & IDX_MASK;
            if (k >= lo) {
                __builtin_prefetch(&vals[cur], 0, 0);
                stack[sp++] = cur;
                if (k == lo) break;
                cur = l;
            } else {
                cur = r;
            }
        }
    }

    /* Phase 3: Iterative in-order traversal */
    size_t count = 0;
    while (sp > 0) {
        uint32_t cur = stack[--sp];
        const RBNode *n = &nodes[cur];
        out_keys[count] = n->key;
        out_vals[count] = vals[cur];
        count++;
        if (__builtin_expect(count == limit, 0)) return count;

        uint32_t r = n->ch[1] & IDX_MASK;
        if (sp > 0) {
            /* Fast path: stack[sp-1] <= hi, so all keys in r's subtree are < hi */
            while (r != 0) {
                const RBNode *rn = &nodes[r];
                uint32_t rl = rn->ch[0] & IDX_MASK;
                uint32_t rr = rn->ch[1] & IDX_MASK;
                if (rl == 0) {
                    __builtin_prefetch(&vals[rr], 0, 0);
                    out_keys[count] = rn->key;
                    out_vals[count] = vals[r];
                    count++;
                    if (__builtin_expect(count == limit, 0)) return count;
                    r = rr;
                } else {
                    __builtin_prefetch(&nodes[rr], 0, 3);
                    __builtin_prefetch(&vals[rl], 0, 0);
                    __builtin_prefetch(&vals[r], 0, 0);
                    stack[sp++] = r;
                    r = rl;
                }
            }
        } else {
            /* Boundary path: keys in r's subtree may exceed hi */
            while (r != 0) {
                const RBNode *rn = &nodes[r];
                int64_t rk = rn->key;
                uint32_t rl = rn->ch[0] & IDX_MASK;
                uint32_t rr = rn->ch[1] & IDX_MASK;
                if (rk <= hi) {
                    if (rl == 0) {
                        out_keys[count] = rk;
                        out_vals[count] = vals[r];
                        count++;
                        if (__builtin_expect(count == limit, 0)) return count;
                        r = rr;
                    } else {
                        __builtin_prefetch(&nodes[rr], 0, 3);
                        __builtin_prefetch(&vals[r], 0, 0);
                        stack[sp++] = r;
                        r = rl;
                    }
                } else {
                    r = rl;
                }
            }
        }
    }

    return count;
}

size_t rbtree_len(const rbtree *t) {
    return (size_t)t->len;
}

static size_t height_rec(const RBNode *nodes, uint32_t x) {
    if (x == 0) return 0;
    size_t lh = height_rec(nodes, nodes[x].ch[0] & IDX_MASK);
    size_t rh = height_rec(nodes, nodes[x].ch[1] & IDX_MASK);
    return 1u + (lh > rh ? lh : rh);
}

size_t rbtree_height(const rbtree *t) {
    return height_rec(t->nodes, t->root);
}
