const std = @import("std");
const builtin = @import("builtin");

const NIL: u32 = 0;
const RED_BIT: u32 = 0x8000_0000;
const IDX_MASK: u32 = 0x7FFF_FFFF;
const MAX_BLOCKS: usize = (IDX_MASK / 16);
const IS_LITTLE_ENDIAN = builtin.cpu.arch.endian() == .little;

const Node = extern struct {
    key: i64,
    // child[0]: bit 31 = is_red (1 = red, 0 = black), bits 0..30 = left word index
    // child[1]: bits 0..30 = right word index (bit 31 always 0)
    child: [2]u32,
    val: i64,
};

// Five 24-byte nodes (120 bytes) packed into each 128-byte Apple Silicon cache line.
// Every node sits entirely within a single 128-byte cache line (zero cache-line splits),
// and nodes are addressed by 8-byte word index (b*16 + s*3) so address calculation is
// a single shifted add: `words + idx` (base + idx * 8).
const Block = extern struct {
    words: [16]u64 align(128),
};

comptime {
    if (@sizeOf(Node) != 24) @compileError("Node must be 24 bytes");
    if (@alignOf(Node) != 8) @compileError("Node must be 8-byte aligned");
    if (@sizeOf(Block) != 128) @compileError("Block must be 128 bytes");
    if (@alignOf(Block) != 128) @compileError("Block must be 128-byte aligned");
}

const RangeFrame = struct {
    key: i64,
    val: i64,
    right: u32,
};

pub const RBTree = struct {
    allocator: std.mem.Allocator,
    blocks: []Block,
    root: u32,
    count: usize,
    next_idx: u32,
    free_head: u32,

    pub fn init(allocator: std.mem.Allocator) RBTree {
        return .{
            .allocator = allocator,
            .blocks = &.{},
            .root = NIL,
            .count = 0,
            .next_idx = 3, // word 0..2 is the black NIL sentinel
            .free_head = NIL,
        };
    }

    pub fn deinit(self: *RBTree) void {
        if (self.blocks.len > 0) {
            self.allocator.free(self.blocks);
            self.blocks = &.{};
        }
        self.root = NIL;
        self.count = 0;
        self.next_idx = 3;
        self.free_head = NIL;
    }

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

    inline fn loadChildren(node: *const Node) struct { left: u32, right: u32 } {
        if (IS_LITTLE_ENDIAN) {
            const pair: u64 = @bitCast(node.child);
            return .{
                .left = @as(u32, @truncate(pair)) & IDX_MASK,
                .right = @truncate(pair >> 32),
            };
        } else {
            return .{
                .left = node.child[0] & IDX_MASK,
                .right = node.child[1],
            };
        }
    }

    inline fn getChild(node: *const Node, d: u1) u32 {
        return node.child[d] & IDX_MASK;
    }

    inline fn setChild(node: *Node, d: u1, c: u32) void {
        node.child[d] = (node.child[d] & RED_BIT) | c;
    }

    inline fn isRedNode(node: *const Node) bool {
        return (node.child[0] & RED_BIT) != 0;
    }

    inline fn isRed(words: [*]align(128) u64, idx: u32) bool {
        const node: *const Node = @ptrCast(words + idx);
        return (node.child[0] & RED_BIT) != 0;
    }

    inline fn setRed(node: *Node) void {
        node.child[0] |= RED_BIT;
    }

    inline fn setBlack(node: *Node) void {
        node.child[0] &= IDX_MASK;
    }

    inline fn setColor(node: *Node, red: bool) void {
        node.child[0] = (node.child[0] & IDX_MASK) | (if (red) RED_BIT else 0);
    }

    inline fn rotate(words: [*]align(128) u64, x_idx: u32, d: u1) u32 {
        const opp: u1 = 1 - d;
        const x: *Node = @ptrCast(words + x_idx);
        const y_idx = getChild(x, opp);
        const y: *Node = @ptrCast(words + y_idx);
        const mid = getChild(y, d);
        setChild(x, opp, mid);
        setChild(y, d, x_idx);
        return y_idx;
    }

    fn grow(self: *RBTree) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        if (self.blocks.len == 0) {
            const new_blocks = try self.allocator.alloc(Block, 64);
            const words: [*]align(128) u64 = @ptrCast(new_blocks.ptr);
            const nil_node: *Node = @ptrCast(words);
            nil_node.* = .{ .key = 0, .child = .{ NIL, NIL }, .val = 0 };
            self.blocks = new_blocks;
        } else {
            if (self.blocks.len >= MAX_BLOCKS) return error.OutOfMemory;
            const new_cap = @min(self.blocks.len * 2, MAX_BLOCKS);
            self.blocks = try self.allocator.realloc(self.blocks, new_cap);
        }
    }

    inline fn allocNode(self: *RBTree) std.mem.Allocator.Error!u32 {
        if (self.free_head != NIL) {
            const idx = self.free_head;
            const words: [*]align(128) u64 = @ptrCast(self.blocks.ptr);
            const node: *Node = @ptrCast(words + idx);
            self.free_head = node.child[1];
            return idx;
        }
        if (self.next_idx >= self.blocks.len * 16) {
            try self.grow();
        }
        const idx = self.next_idx;
        const step: u32 = if ((idx & 15) == 12) 4 else 3;
        self.next_idx = idx + step;
        return idx;
    }

    pub fn get(self: *const RBTree, key: i64) ?i64 {
        var cur = self.root;
        if (cur == NIL) return null;
        const words: [*]align(128) const u64 = @ptrCast(self.blocks.ptr);
        while (cur != NIL) {
            const node: *const Node = @ptrCast(words + cur);
            const k = node.key;
            const ch = loadChildren(node);
            if (k == key) {
                @branchHint(.unlikely);
                return node.val;
            }
            cur = if (key < k) ch.left else ch.right;
        }
        return null;
    }

    pub fn insert(self: *RBTree, key: i64, value: i64) std.mem.Allocator.Error!bool {
        if (self.root == NIL) {
            @branchHint(.unlikely);
            const idx = try self.allocNode();
            const words: [*]align(128) u64 = @ptrCast(self.blocks.ptr);
            const node: *Node = @ptrCast(words + idx);
            node.* = .{ .key = key, .child = .{ NIL, NIL }, .val = value };
            self.root = idx;
            self.count = 1;
            return true;
        }

        var path: [66]u32 = undefined;
        var dirs: [66]u1 = undefined;
        var words: [*]align(128) u64 = @ptrCast(self.blocks.ptr);
        var cur = self.root;
        var depth: usize = 0;

        while (cur != NIL) {
            const node: *Node = @ptrCast(words + cur);
            const k = node.key;
            const ch = loadChildren(node);
            if (k == key) {
                @branchHint(.unlikely);
                node.val = value;
                return false;
            }
            const go_right: u1 = @intFromBool(key > k);
            path[depth] = cur;
            dirs[depth] = go_right;
            depth += 1;
            cur = if (go_right == 0) ch.left else ch.right;
        }

        const new_idx = try self.allocNode();
        words = @ptrCast(self.blocks.ptr);
        const new_node: *Node = @ptrCast(words + new_idx);
        new_node.* = .{
            .key = key,
            .child = .{ RED_BIT | NIL, NIL },
            .val = value,
        };
        self.count += 1;

        depth -= 1;
        const p_idx = path[depth];
        const p_dir = dirs[depth];
        const p_node: *Node = @ptrCast(words + p_idx);
        setChild(p_node, p_dir, new_idx);

        if (!isRedNode(p_node)) return true;

        while (true) {
            const cur_p_idx = path[depth];
            const cur_p: *Node = @ptrCast(words + cur_p_idx);
            if (!isRedNode(cur_p)) break;

            // Root is always black and cur_p is red, so depth >= 1 is guaranteed.
            const g_idx = path[depth - 1];
            const g_dir = dirs[depth - 1];
            const g: *Node = @ptrCast(words + g_idx);
            const u_idx = getChild(g, 1 - g_dir);

            if (isRed(words, u_idx)) {
                setBlack(cur_p);
                const u: *Node = @ptrCast(words + u_idx);
                setBlack(u);
                if (depth == 1) break;
                setRed(g);
                depth -= 2;
                continue;
            }

            const cur_z_dir = dirs[depth];
            var top_idx: u32 = undefined;
            if (cur_z_dir != g_dir) {
                // Direct double rotation (triangle case)
                const z_idx = getChild(cur_p, cur_z_dir);
                const z: *Node = @ptrCast(words + z_idx);
                setChild(cur_p, cur_z_dir, getChild(z, g_dir));
                setChild(g, g_dir, getChild(z, cur_z_dir));
                setChild(z, g_dir, cur_p_idx);
                setChild(z, cur_z_dir, g_idx);
                setBlack(z);
                setRed(g);
                top_idx = z_idx;
            } else {
                // Single rotation (line case)
                setBlack(cur_p);
                setRed(g);
                top_idx = rotate(words, g_idx, 1 - g_dir);
            }

            if (depth == 1) {
                self.root = top_idx;
            } else {
                const gg: *Node = @ptrCast(words + path[depth - 2]);
                setChild(gg, dirs[depth - 2], top_idx);
            }
            break;
        }

        return true;
    }

    pub fn remove(self: *RBTree, key: i64) bool {
        var cur = self.root;
        if (cur == NIL) return false;

        var path: [66]u32 = undefined;
        var dirs: [66]u1 = undefined;
        const words: [*]align(128) u64 = @ptrCast(self.blocks.ptr);
        var depth: usize = 0;

        var t_left: u32 = NIL;
        var t_right: u32 = NIL;
        while (cur != NIL) {
            const node: *Node = @ptrCast(words + cur);
            const k = node.key;
            const ch = loadChildren(node);
            if (k == key) {
                @branchHint(.unlikely);
                t_left = ch.left;
                t_right = ch.right;
                break;
            }
            const go_right: u1 = @intFromBool(key > k);
            path[depth] = cur;
            dirs[depth] = go_right;
            depth += 1;
            cur = if (go_right == 0) ch.left else ch.right;
        }

        if (cur == NIL) return false;

        var del_idx = cur;
        const t_node: *Node = @ptrCast(words + cur);

        if (t_left != NIL and t_right != NIL) {
            // Find in-order successor (leftmost node in right subtree)
            path[depth] = cur;
            dirs[depth] = 1;
            depth += 1;
            var s_idx = t_right;
            var s_node: *Node = @ptrCast(words + s_idx);
            while (true) {
                const sl = s_node.child[0] & IDX_MASK;
                if (sl == NIL) break;
                path[depth] = s_idx;
                dirs[depth] = 0;
                depth += 1;
                s_idx = sl;
                s_node = @ptrCast(words + s_idx);
            }
            t_node.key = s_node.key;
            t_node.val = s_node.val;
            del_idx = s_idx;
        }

        const del_node: *Node = @ptrCast(words + del_idx);
        const del_was_red = isRedNode(del_node);
        const dl = del_node.child[0] & IDX_MASK;
        const dr = del_node.child[1];
        const rep_idx = if (dl != NIL) dl else dr;

        if (self.count == 1) {
            self.count = 0;
            self.root = NIL;
            self.next_idx = 3;
            self.free_head = NIL;
            return true;
        }

        if (depth == 0) {
            self.root = rep_idx;
        } else {
            const p: *Node = @ptrCast(words + path[depth - 1]);
            setChild(p, dirs[depth - 1], rep_idx);
        }

        // Return deleted node to free list
        self.count -= 1;
        del_node.child[1] = self.free_head;
        self.free_head = del_idx;

        if (del_was_red) return true;

        if (rep_idx != NIL) {
            const rep: *Node = @ptrCast(words + rep_idx);
            setBlack(rep);
            return true;
        }

        // Deleted node was a black leaf -> fix double-black upwards
        while (depth > 0) {
            const p_idx = path[depth - 1];
            const d = dirs[depth - 1];
            const opp: u1 = 1 - d;
            const p: *Node = @ptrCast(words + p_idx);
            var w_idx = getChild(p, opp);
            var w: *Node = @ptrCast(words + w_idx);

            // Case 1: Sibling is red -> rotate to make sibling black
            if (isRedNode(w)) {
                setBlack(w);
                setRed(p);
                const new_top = rotate(words, p_idx, d);
                if (depth == 1) {
                    self.root = new_top;
                } else {
                    const gp: *Node = @ptrCast(words + path[depth - 2]);
                    setChild(gp, dirs[depth - 2], new_top);
                }
                path[depth - 1] = new_top;
                dirs[depth - 1] = d;
                path[depth] = p_idx;
                dirs[depth] = d;
                depth += 1;
                w_idx = getChild(p, opp);
                w = @ptrCast(words + w_idx);
            }

            const near_idx = getChild(w, d);
            const far_idx = getChild(w, opp);

            if (!isRed(words, far_idx)) {
                if (!isRed(words, near_idx)) {
                    // Case 2: Both nephews are black
                    setRed(w);
                    if (isRedNode(p)) {
                        setBlack(p);
                        break;
                    }
                    depth -= 1;
                    continue;
                }

                // Case 3 + Case 4 combined: near nephew is red, far nephew is black
                const near: *Node = @ptrCast(words + near_idx);
                setColor(near, isRedNode(p));
                setBlack(p);
                setChild(p, opp, getChild(near, d));
                setChild(w, d, getChild(near, opp));
                setChild(near, d, p_idx);
                setChild(near, opp, w_idx);
                if (depth == 1) {
                    self.root = near_idx;
                } else {
                    const gp: *Node = @ptrCast(words + path[depth - 2]);
                    setChild(gp, dirs[depth - 2], near_idx);
                }
                break;
            }

            // Case 4: Far nephew is red
            setColor(w, isRedNode(p));
            setBlack(p);
            const far: *Node = @ptrCast(words + far_idx);
            setBlack(far);
            const top_idx = rotate(words, p_idx, d);
            if (depth == 1) {
                self.root = top_idx;
            } else {
                const gp: *Node = @ptrCast(words + path[depth - 2]);
                setChild(gp, dirs[depth - 2], top_idx);
            }
            break;
        }

        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 (self.root == NIL or lo > hi or limit == 0) return 0;

        const words: [*]align(128) const u64 = @ptrCast(self.blocks.ptr);
        var stack: [66]RangeFrame = undefined;
        var sp: usize = 0;
        var count: usize = 0;

        // Initial descent to locate the smallest key >= lo.
        // Only push ancestors with lo < key <= hi (and non-NIL left subtree).
        var p = self.root;
        while (p != NIL) {
            const node: *const Node = @ptrCast(words + p);
            const k = node.key;
            if (k < lo) {
                p = node.child[1];
            } else if (k == lo) {
                out_keys[count] = k;
                out_vals[count] = node.val;
                count += 1;
                if (count == limit) return count;
                p = if (k < hi) node.child[1] else NIL;
                break;
            } else if (k <= hi) {
                const l = node.child[0] & IDX_MASK;
                const r = if (k < hi) node.child[1] else NIL;
                if (l == NIL) {
                    out_keys[count] = k;
                    out_vals[count] = node.val;
                    count += 1;
                    if (count == limit) return count;
                    p = r;
                    break;
                }
                stack[sp] = .{ .key = k, .val = node.val, .right = r };
                sp += 1;
                p = l;
            } else {
                p = node.child[0] & IDX_MASK;
            }
        }

        // Main in-order traversal over [lo, hi]
        while (true) {
            while (p != NIL) {
                const node: *const Node = @ptrCast(words + p);
                const k = node.key;
                if (k <= hi) {
                    const l = node.child[0] & IDX_MASK;
                    const r = if (k < hi) node.child[1] else NIL;
                    if (l == NIL) {
                        out_keys[count] = k;
                        out_vals[count] = node.val;
                        count += 1;
                        if (count == limit) return count;
                        p = r;
                    } else {
                        // Prefetch right child while traversing left subtree for MLP
                        @prefetch(words + r, .{ .rw = .read, .locality = 3, .cache = .data });
                        stack[sp] = .{ .key = k, .val = node.val, .right = r };
                        sp += 1;
                        p = l;
                    }
                } else {
                    p = node.child[0] & IDX_MASK;
                }
            }

            if (sp == 0) break;
            sp -= 1;
            const frame = stack[sp];
            out_keys[count] = frame.key;
            out_vals[count] = frame.val;
            count += 1;
            if (count == limit) return count;
            p = frame.right;
        }

        return count;
    }

    pub fn height(self: *const RBTree) usize {
        if (self.root == NIL) return 0;
        const words: [*]align(128) const u64 = @ptrCast(self.blocks.ptr);
        return heightRec(words, self.root);
    }

    fn heightRec(words: [*]align(128) const u64, idx: u32) usize {
        if (idx == NIL) return 0;
        const node: *const Node = @ptrCast(words + idx);
        const lh = heightRec(words, node.child[0] & IDX_MASK);
        const rh = heightRec(words, node.child[1]);
        return 1 + @max(lh, rh);
    }
};
