#pragma once

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <optional>
#include <type_traits>

class RBTree {
public:
    RBTree() noexcept
        : nodes_(nullptr), cap_(0), pool_used_(0), free_head_(0), root_(0), len_(0) {}

    ~RBTree() noexcept {
        std::free(nodes_);
    }

    RBTree(const RBTree&) = delete;
    RBTree& operator=(const RBTree&) = delete;

    bool insert(std::int64_t key, std::int64_t value) {
        if (root_ == 0) [[unlikely]] {
            root_ = alloc_node(key, value, false);
            len_ = 1;
            return true;
        }

        std::uint32_t path[64];
        std::uint8_t dirs[64];
        int depth = 0;

        Node* __restrict ns = nodes_;
        std::uint32_t cur = root_;
        while (cur != 0) {
            Node& nd = ns[cur];
            std::int64_t k = nd.key;
            std::uint32_t l = nd.child[0] & IDX_MASK;
            std::uint32_t r = nd.child[1];
            if (key == k) [[unlikely]] {
                nd.val = value;
                return false;
            }
            std::uint8_t dir = (key > k);
            path[depth] = cur;
            dirs[depth] = dir;
            depth++;
            cur = dir ? r : l;
        }

        std::uint32_t x = alloc_node(key, value, true);
        ++len_;

        int idx = depth - 1;
        std::uint32_t p = path[idx];
        set_child(p, dirs[idx], x);

        if (!is_red(p)) {
            return true;
        }

        // Bottom-up rebalance: x is RED, p = path[idx] is RED.
        // Since root_ is always BLACK, idx >= 1 and g = path[idx - 1] is BLACK.
        while (true) {
            std::uint32_t g = path[idx - 1];
            std::uint8_t g_dir = dirs[idx - 1];
            std::uint8_t opp = g_dir ^ 1;
            std::uint32_t u = get_child(g, opp);

            if (is_red(u)) {
                set_black(p);
                set_black(u);
                if (idx == 1) {
                    return true;
                }
                set_red(g);
                x = g;
                idx -= 2;
                p = path[idx];
                if (!is_red(p)) {
                    return true;
                }
            } else {
                std::uint8_t p_dir = dirs[idx];
                std::uint32_t top;
                if (p_dir == g_dir) {
                    set_black(p);
                    set_red(g);
                    top = rotate(g, opp);
                } else {
                    set_black(x);
                    set_red(g);
                    std::uint32_t xd = get_child(x, g_dir);
                    std::uint32_t xo = get_child(x, opp);
                    set_child(p, opp, xd);
                    set_child(g, g_dir, xo);
                    set_child(x, g_dir, p);
                    set_child(x, opp, g);
                    top = x;
                }
                if (idx == 1) {
                    root_ = top;
                } else {
                    set_child(path[idx - 2], dirs[idx - 2], top);
                }
                return true;
            }
        }
    }

    std::optional<std::int64_t> get(std::int64_t key) const noexcept {
        const Node* __restrict ns = nodes_;
        std::uint32_t cur = root_;
        while (cur != 0) {
            const Node& nd = ns[cur];
            std::int64_t k = nd.key;
            std::uint32_t l = nd.child[0] & IDX_MASK;
            std::uint32_t r = nd.child[1];
            if (key == k) [[unlikely]] {
                return nd.val;
            }
            cur = (key > k) ? r : l;
        }
        return std::nullopt;
    }

    bool remove(std::int64_t key) noexcept {
        if (root_ == 0) [[unlikely]] {
            return false;
        }

        std::uint32_t path[64];
        std::uint8_t dirs[64];
        int depth = 0;

        Node* __restrict ns = nodes_;
        std::uint32_t cur = root_;
        while (cur != 0) {
            const Node& nd = ns[cur];
            std::int64_t k = nd.key;
            std::uint32_t l = nd.child[0] & IDX_MASK;
            std::uint32_t r = nd.child[1];
            if (key == k) [[unlikely]] {
                break;
            }
            std::uint8_t dir = (key > k);
            path[depth] = cur;
            dirs[depth] = dir;
            depth++;
            cur = dir ? r : l;
        }
        if (cur == 0) {
            return false;
        }

        if (--len_ == 0) [[unlikely]] {
            root_ = 0;
            pool_used_ = 1;
            free_head_ = 0;
            return true;
        }

        std::uint32_t cl = get_left(cur);
        std::uint32_t cr = get_right(cur);
        if (cl != 0 && cr != 0) {
            // Find in-order successor (minimum of right subtree).
            std::uint32_t target = cur;
            path[depth] = target;
            dirs[depth] = 1;
            depth++;

            cur = cr;
            while (true) {
                std::uint32_t sl = get_left(cur);
                if (sl == 0) break;
                path[depth] = cur;
                dirs[depth] = 0;
                depth++;
                cur = sl;
            }
            ns[target].key = ns[cur].key;
            ns[target].val = ns[cur].val;
            cl = 0;
            cr = get_right(cur);
        }

        // Now cur has at most one non-zero child.
        std::uint32_t child = cl | cr;
        bool cur_was_red = is_red(cur);

        if (depth == 0) [[unlikely]] {
            root_ = child;
            set_black(child);
            free_node(cur);
            return true;
        }

        int idx = depth - 1;
        set_child(path[idx], dirs[idx], child);
        free_node(cur);

        if (cur_was_red) {
            return true;
        }
        if (is_red(child)) {
            set_black(child);
            return true;
        }

        // Double-black fixup at path[idx].child[dirs[idx]].
        while (true) {
            std::uint32_t p = path[idx];
            std::uint8_t d = dirs[idx];
            std::uint8_t opp = d ^ 1;
            std::uint32_t s = get_child(p, opp);

            std::uint32_t gp = (idx > 0) ? path[idx - 1] : 0;
            std::uint8_t gp_dir = (idx > 0) ? dirs[idx - 1] : 0;

            if (is_red(s)) {
                // Case 1: Red sibling -> rotate p in direction d.
                set_black(s);
                set_red(p);
                rotate(p, d);
                if (gp == 0) {
                    root_ = s;
                } else {
                    set_child(gp, gp_dir, s);
                }
                gp = s;
                gp_dir = d;
                s = get_child(p, opp);
            }

            std::uint32_t sf = get_child(s, opp);
            if (is_red(sf)) {
                // Case 4: Far nephew is RED.
                copy_color(s, p);
                set_black(p);
                set_black(sf);
                rotate(p, d);
                if (gp == 0) {
                    root_ = s;
                } else {
                    set_child(gp, gp_dir, s);
                }
                return true;
            }

            std::uint32_t sn = get_child(s, d);
            if (is_red(sn)) {
                // Case 3 + 4 fused: Near nephew is RED, far nephew is BLACK.
                copy_color(sn, p);
                set_black(p);
                std::uint32_t sn_d = get_child(sn, d);
                std::uint32_t sn_o = get_child(sn, opp);
                set_child(p, opp, sn_d);
                set_child(s, d, sn_o);
                set_child(sn, d, p);
                set_child(sn, opp, s);
                if (gp == 0) {
                    root_ = sn;
                } else {
                    set_child(gp, gp_dir, sn);
                }
                return true;
            }

            // Case 2: Both nephews are BLACK.
            set_red(s);
            if (is_red(p)) {
                set_black(p);
                return true;
            }
            if (idx == 0) {
                return true;
            }
            idx--;
        }
    }

    std::size_t range(std::int64_t lo, std::int64_t hi,
                      std::int64_t* out_keys, std::int64_t* out_vals,
                      std::size_t limit) const noexcept {
        if (lo > hi || limit == 0 || root_ == 0) {
            return 0;
        }

        const Node* __restrict ns = nodes_;
        std::int64_t* __restrict ok = out_keys;
        std::int64_t* __restrict ov = out_vals;
        std::uint32_t stack[64];
        int sp = 0;
        std::size_t count = 0;

        std::uint32_t cur = root_;
        std::uint32_t r = 0;
        while (cur != 0) {
            const Node& nc = ns[cur];
            std::int64_t k = nc.key;
            std::uint32_t l = nc.child[0] & IDX_MASK;
            std::uint32_t rc = nc.child[1];
            if (k >= lo && k <= hi) [[unlikely]] {
                if (k == lo) {
                    ok[0] = k;
                    ov[0] = nc.val;
                    count = 1;
                    if (limit == 1 || k == hi) {
                        return 1;
                    }
                    r = rc;
                    break;
                }
                stack[sp++] = cur;
                if (rc != 0 && k < hi) {
                    __builtin_prefetch(&ns[rc], 0, 3);
                }
                cur = l;
            } else {
                cur = (k < lo) ? rc : l;
            }
        }

        while (true) {
            while (r != 0) {
                const Node& nr = ns[r];
                std::int64_t k = nr.key;
                std::uint32_t nl = nr.child[0] & IDX_MASK;
                if (k > hi) [[unlikely]] {
                    r = nl;
                } else if (nl == 0) {
                    ok[count] = k;
                    ov[count] = nr.val;
                    if (++count == limit || k == hi) {
                        return count;
                    }
                    r = nr.child[1];
                } else {
                    stack[sp++] = r;
                    std::uint32_t nr_r = nr.child[1];
                    if (nr_r != 0) {
                        __builtin_prefetch(&ns[nr_r], 0, 3);
                    }
                    r = nl;
                }
            }
            if (sp == 0) {
                break;
            }
            std::uint32_t u = stack[--sp];
            const Node& nu = ns[u];
            std::int64_t k = nu.key;
            ok[count] = k;
            ov[count] = nu.val;
            if (++count == limit || k == hi) {
                return count;
            }
            r = nu.child[1];
        }
        return count;
    }

    std::size_t len() const noexcept {
        return len_;
    }

    std::size_t height() const noexcept {
        return height_rec(root_);
    }

private:
    static constexpr std::uint32_t RED_BIT  = 0x80000000u;
    static constexpr std::uint32_t IDX_MASK = 0x7FFFFFFFu;

    struct Node {
        std::int64_t key;
        std::uint32_t child[2]; // child[0]: bit 31 = color (1=RED, 0=BLACK), bits 0..30 = left
        std::int64_t val;
    };
    static_assert(sizeof(Node) == 24);
    static_assert(std::is_trivially_copyable_v<Node>);

    Node* nodes_;
    std::size_t cap_;
    std::uint32_t pool_used_;
    std::uint32_t free_head_;
    std::uint32_t root_;
    std::size_t len_;

    bool is_red(std::uint32_t u) const noexcept {
        return (nodes_[u].child[0] & RED_BIT) != 0;
    }

    void set_red(std::uint32_t u) noexcept {
        nodes_[u].child[0] |= RED_BIT;
    }

    void set_black(std::uint32_t u) noexcept {
        nodes_[u].child[0] &= IDX_MASK;
    }

    void copy_color(std::uint32_t dst, std::uint32_t src) noexcept {
        nodes_[dst].child[0] = (nodes_[dst].child[0] & IDX_MASK) | (nodes_[src].child[0] & RED_BIT);
    }

    std::uint32_t get_left(std::uint32_t u) const noexcept {
        return nodes_[u].child[0] & IDX_MASK;
    }

    std::uint32_t get_right(std::uint32_t u) const noexcept {
        return nodes_[u].child[1];
    }

    std::uint32_t get_child(std::uint32_t u, std::uint8_t d) const noexcept {
        return nodes_[u].child[d] & IDX_MASK;
    }

    void set_child(std::uint32_t u, std::uint8_t d, std::uint32_t c) noexcept {
        nodes_[u].child[d] = (nodes_[u].child[d] & RED_BIT) | c;
    }

    // Rotate subtree rooted at u in direction d (d=0: left rotate, d=1: right rotate).
    // Returns the new root of this subtree.
    std::uint32_t rotate(std::uint32_t u, std::uint8_t d) noexcept {
        std::uint8_t opp = d ^ 1;
        std::uint32_t y = get_child(u, opp);
        std::uint32_t beta = get_child(y, d);
        set_child(u, opp, beta);
        set_child(y, d, u);
        return y;
    }

    [[gnu::noinline]] void grow() {
        std::size_t new_cap = (cap_ == 0) ? 256 : (cap_ * 2);
        Node* new_nodes;
        if (cap_ == 0) {
            new_nodes = static_cast<Node*>(std::malloc(new_cap * sizeof(Node)));
            if (!new_nodes) std::abort();
            new_nodes[0] = Node{0, {0, 0}, 0};
            pool_used_ = 1;
        } else {
            new_nodes = static_cast<Node*>(std::realloc(nodes_, new_cap * sizeof(Node)));
            if (!new_nodes) std::abort();
        }
        nodes_ = new_nodes;
        cap_ = new_cap;
    }

    std::uint32_t alloc_node(std::int64_t key, std::int64_t value, bool red) {
        std::uint32_t idx;
        if (free_head_ != 0) {
            idx = free_head_;
            free_head_ = nodes_[idx].child[1];
        } else {
            if (pool_used_ == cap_) [[unlikely]] {
                grow();
            }
            idx = pool_used_++;
        }
        Node& nd = nodes_[idx];
        nd.key = key;
        nd.child[0] = red ? RED_BIT : 0u;
        nd.child[1] = 0u;
        nd.val = value;
        return idx;
    }

    void free_node(std::uint32_t u) noexcept {
        nodes_[u].child[1] = free_head_;
        free_head_ = u;
    }

    std::size_t height_rec(std::uint32_t u) const noexcept {
        if (u == 0) return 0;
        std::size_t hl = height_rec(get_left(u));
        std::size_t hr = height_rec(get_right(u));
        return 1 + (hl > hr ? hl : hr);
    }
};
