// Red-black tree (CLRS-style, bottom-up rebalancing) mapping i64 -> i64.
//
// Layout: nodes live in one contiguous, geometrically grown array and are
// linked by 32-bit indices. Index 0 is a black sentinel (NIL). A node is 24
// bytes: key, two child links, value. The node's colour is stored in bit 31
// of its left link (set = red). There are no parent links: insert and remove
// record the search path on a small stack and rebalance bottom-up from it.
// Freed nodes go on a free list threaded through link[1].

const std = @import("std");

const NIL: u32 = 0;
const RED: u32 = 0x8000_0000;
const IDX: u32 = 0x7FFF_FFFF;
const MAX_DEPTH = 128;

const Node = extern struct {
    key: i64,
    link: [2]u32, // link[0] bit 31 = red flag
    value: i64,
};

comptime {
    std.debug.assert(@sizeOf(Node) == 24);
}

pub const RBTree = struct {
    nodes: [*]Node,
    cap: u32, // number of slots allocated (0 = none)
    used: u32, // slots handed out so far by bump allocation (incl. sentinel)
    free_head: u32,
    root: u32,
    count: usize,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) RBTree {
        return .{
            .nodes = undefined,
            .cap = 0,
            .used = 0,
            .free_head = NIL,
            .root = NIL,
            .count = 0,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *RBTree) void {
        if (self.cap != 0) self.allocator.free(self.nodes[0..self.cap]);
        self.* = init(self.allocator);
    }

    // ------------------------------------------------------------ helpers

    inline fn at(self: *const RBTree, i: u32) *Node {
        return &self.nodes[i];
    }

    inline fn child(self: *const RBTree, i: u32, d: u1) u32 {
        return self.nodes[i].link[d] & IDX;
    }

    inline fn setChild(self: *const RBTree, i: u32, d: u1, c: u32) void {
        const p = &self.nodes[i].link[d];
        p.* = (p.* & RED) | c;
    }

    inline fn isRed(self: *const RBTree, i: u32) bool {
        return (self.nodes[i].link[0] & RED) != 0;
    }

    inline fn setRed(self: *const RBTree, i: u32) void {
        self.nodes[i].link[0] |= RED;
    }

    inline fn setBlack(self: *const RBTree, i: u32) void {
        self.nodes[i].link[0] &= IDX;
    }

    // Rotate the subtree rooted at x so that its child on side !d comes up.
    // Returns the new subtree root.
    inline fn rotate(self: *const RBTree, x: u32, d: u1) u32 {
        const y = self.child(x, ~d);
        self.setChild(x, ~d, self.child(y, d));
        self.setChild(y, d, x);
        return y;
    }

    fn grow(self: *RBTree) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        if (self.cap == 0) {
            const initial: u32 = 256;
            const mem = try self.allocator.alloc(Node, initial);
            self.nodes = mem.ptr;
            self.cap = initial;
            mem[0] = .{ .key = 0, .link = .{ 0, 0 }, .value = 0 }; // black sentinel
            self.used = 1;
            return;
        }
        const old = self.cap;
        if (old >= (IDX >> 1)) return error.OutOfMemory;
        const new_cap: u32 = old * 2;
        const mem = try self.allocator.realloc(self.nodes[0..old], new_cap);
        self.nodes = mem.ptr;
        self.cap = new_cap;
    }

    inline fn allocNode(self: *RBTree, key: i64, value: i64) std.mem.Allocator.Error!u32 {
        var idx: u32 = undefined;
        if (self.free_head != NIL) {
            idx = self.free_head;
            self.free_head = self.nodes[idx].link[1];
        } else {
            if (self.used >= self.cap) try self.grow();
            idx = self.used;
            self.used += 1;
        }
        self.nodes[idx] = .{ .key = key, .link = .{ RED, NIL }, .value = value };
        return idx;
    }

    inline fn freeNode(self: *RBTree, idx: u32) void {
        self.nodes[idx].link[1] = self.free_head;
        self.free_head = idx;
    }

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

    pub fn len(self: *const RBTree) usize {
        return self.count;
    }

    pub fn get(self: *const RBTree, key: i64) ?i64 {
        const nodes = self.nodes;
        var x = self.root;
        while (x != NIL) {
            const n = &nodes[x];
            const k = n.key;
            if (k == key) return n.value;
            x = n.link[@intFromBool(k < key)] & IDX;
        }
        return null;
    }

    pub fn insert(self: *RBTree, key: i64, value: i64) std.mem.Allocator.Error!bool {
        if (self.root == NIL) {
            const z = try self.allocNode(key, value);
            self.setBlack(z);
            self.root = z;
            self.count = 1;
            return true;
        }

        var path: [MAX_DEPTH]u32 = undefined;
        var dirs: [MAX_DEPTH]u1 = undefined;
        var depth: usize = 0;
        {
            const nodes = self.nodes;
            var x = self.root;
            while (true) {
                const n = &nodes[x];
                const k = n.key;
                if (k == key) {
                    n.value = value;
                    return false;
                }
                const d: u1 = @intFromBool(k < key);
                path[depth] = x;
                dirs[depth] = d;
                depth += 1;
                const c = n.link[d] & IDX;
                if (c == NIL) break;
                x = c;
            }
        }

        const z = try self.allocNode(key, value); // may move self.nodes
        self.setChild(path[depth - 1], dirs[depth - 1], z);
        self.count += 1;

        // z is at stack position zi (its parent is path[zi-1]).
        var zi = depth;
        while (zi >= 2) {
            const p = path[zi - 1];
            if (!self.isRed(p)) break;
            const g = path[zi - 2];
            const pd = dirs[zi - 2];
            const u = self.child(g, ~pd);
            if (self.isRed(u)) {
                self.setBlack(p);
                self.setBlack(u);
                self.setRed(g);
                zi -= 2;
                continue;
            }
            var top = p;
            if (dirs[zi - 1] != pd) {
                top = self.rotate(p, pd);
                self.setChild(g, pd, top);
            }
            self.setBlack(top);
            self.setRed(g);
            const r = self.rotate(g, ~pd);
            if (zi == 2) {
                self.root = r;
            } else {
                self.setChild(path[zi - 3], dirs[zi - 3], r);
            }
            break;
        }
        self.setBlack(self.root);
        return true;
    }

    pub fn remove(self: *RBTree, key: i64) bool {
        var path: [MAX_DEPTH]u32 = undefined;
        var dirs: [MAX_DEPTH]u1 = undefined;
        var depth: usize = 0;
        const nodes = self.nodes;

        var x = self.root;
        while (true) {
            if (x == NIL) return false;
            const n = &nodes[x];
            const k = n.key;
            if (k == key) break;
            const d: u1 = @intFromBool(k < key);
            path[depth] = x;
            dirs[depth] = d;
            depth += 1;
            x = n.link[d] & IDX;
        }

        // If x has two children, replace its entry with its successor's and
        // remove the successor node instead.
        const xl = self.child(x, 0);
        const xr = self.child(x, 1);
        var c: u32 = undefined;
        if (xl != NIL and xr != NIL) {
            path[depth] = x;
            dirs[depth] = 1;
            depth += 1;
            var y = xr;
            while (true) {
                const yl = self.child(y, 0);
                if (yl == NIL) break;
                path[depth] = y;
                dirs[depth] = 0;
                depth += 1;
                y = yl;
            }
            nodes[x].key = nodes[y].key;
            nodes[x].value = nodes[y].value;
            c = self.child(y, 1);
            x = y;
        } else {
            c = xl | xr;
        }

        if (depth == 0) {
            self.root = c;
        } else {
            self.setChild(path[depth - 1], dirs[depth - 1], c);
        }
        const was_red = self.isRed(x);
        self.freeNode(x);
        self.count -= 1;

        if (was_red) return true;
        if (self.isRed(c)) {
            self.setBlack(c);
            return true;
        }

        // c (possibly NIL) at stack position zi carries an extra black.
        var zi = depth;
        while (zi > 0) {
            const p = path[zi - 1];
            const d = dirs[zi - 1];
            var s = self.child(p, ~d);
            if (self.isRed(s)) {
                self.setBlack(s);
                self.setRed(p);
                const r = self.rotate(p, d); // r == s
                if (zi == 1) {
                    self.root = r;
                } else {
                    self.setChild(path[zi - 2], dirs[zi - 2], r);
                }
                // Path is now ..., s, p, c.
                path[zi - 1] = r;
                dirs[zi - 1] = d;
                path[zi] = p;
                dirs[zi] = d;
                zi += 1;
                s = self.child(p, ~d);
            }
            const sn = self.child(s, d);
            var sf = self.child(s, ~d);
            if (!self.isRed(sn) and !self.isRed(sf)) {
                self.setRed(s);
                if (self.isRed(p)) {
                    self.setBlack(p);
                    return true;
                }
                zi -= 1;
                continue;
            }
            if (!self.isRed(sf)) {
                self.setBlack(sn);
                self.setRed(s);
                const r = self.rotate(s, ~d); // r == sn
                self.setChild(p, ~d, r);
                sf = s;
                s = r;
            }
            if (self.isRed(p)) self.setRed(s) else self.setBlack(s);
            self.setBlack(p);
            self.setBlack(sf);
            const r = self.rotate(p, d); // r == s
            if (zi == 1) {
                self.root = r;
            } else {
                self.setChild(path[zi - 2], dirs[zi - 2], r);
            }
            return true;
        }
        // Extra black reached the root.
        self.setBlack(self.root);
        return true;
    }

    pub fn range(self: *const RBTree, lo: i64, hi: i64, out_keys: []i64, out_vals: []i64) usize {
        const limit = @min(out_keys.len, out_vals.len);
        if (lo > hi or limit == 0) return 0;
        const nodes = self.nodes;

        var stack: [MAX_DEPTH]u32 = undefined;
        var sp: usize = 0;

        // Push the path of nodes with key >= lo (each is the next in-order
        // candidate after its left subtree).
        var x = self.root;
        while (x != NIL) {
            const n = &nodes[x];
            if (n.key >= lo) {
                if (n.key == lo) {
                    stack[sp] = x;
                    sp += 1;
                    break;
                }
                stack[sp] = x;
                sp += 1;
                x = n.link[0] & IDX;
            } else {
                x = n.link[1];
            }
        }

        var count: usize = 0;
        while (sp > 0) {
            sp -= 1;
            const n = &nodes[stack[sp]];
            if (n.key > hi) break;
            out_keys[count] = n.key;
            out_vals[count] = n.value;
            count += 1;
            if (count == limit) break;
            x = n.link[1];
            while (x != NIL) {
                const m = &nodes[x];
                @prefetch(&nodes[m.link[1]], .{});
                stack[sp] = x;
                sp += 1;
                x = m.link[0] & IDX;
            }
        }
        return count;
    }

    pub fn height(self: *const RBTree) usize {
        if (self.root == NIL) return 0;
        // Iterative DFS with explicit stack of (node, depth).
        var stack: [MAX_DEPTH * 2]struct { n: u32, d: usize } = undefined;
        var sp: usize = 0;
        var best: usize = 0;
        stack[0] = .{ .n = self.root, .d = 1 };
        sp = 1;
        while (sp > 0) {
            sp -= 1;
            const e = stack[sp];
            if (e.d > best) best = e.d;
            const l = self.child(e.n, 0);
            const r = self.child(e.n, 1);
            if (l != NIL) {
                stack[sp] = .{ .n = l, .d = e.d + 1 };
                sp += 1;
            }
            if (r != NIL) {
                stack[sp] = .{ .n = r, .d = e.d + 1 };
                sp += 1;
            }
        }
        return best;
    }
};
