const std = @import("std");

const T: usize = 16;
const MIN_KEYS: usize = T - 1; // 15
const MAX_KEYS: usize = 2 * T - 1; // 31
const MAX_CHILDREN: usize = 2 * T; // 32
const MAX_HEIGHT: usize = 20; // t=16 supports > 16^19 > 2^76 keys

const I64_MAX: i64 = std.math.maxInt(i64);
const NULL_REF: u32 = std.math.maxInt(u32);

/// Cache-line aligned leaf node (512 bytes = 4 x 128-byte M3 cache lines).
/// CL 0 (0..127):   keys[0..15]
/// CL 1 (128..255): keys[16..30] + len (at byte 248)
/// CL 2..3 (256..511): vals[0..30]
/// Invariant: keys[len..31] are always filled with I64_MAX.
const LeafNode = extern struct {
    keys: [MAX_KEYS]i64 align(128),
    len: u8,
    vals: [MAX_KEYS]i64 align(128),
};

/// Cache-line aligned internal node (640 bytes = 5 x 128-byte M3 cache lines).
/// CL 0 (0..127):   keys[0..15]
/// CL 1 (128..255): keys[16..30] + len (at byte 248)
/// CL 2 (256..383): children[0..31] (32-bit pool indices)
/// CL 3..4 (384..639): vals[0..30] (untouched during leaf-bound descents)
/// Invariant: keys[len..31] are always filled with I64_MAX.
const InternalNode = extern struct {
    keys: [MAX_KEYS]i64 align(128),
    len: u8,
    children: [MAX_CHILDREN]u32 align(128),
    vals: [MAX_KEYS]i64 align(128),
};

comptime {
    if (@sizeOf(LeafNode) != 512) @compileError("LeafNode must be 512 bytes");
    if (@alignOf(LeafNode) != 128) @compileError("LeafNode must be 128-byte aligned");
    if (@offsetOf(LeafNode, "keys") != 0) @compileError("LeafNode.keys offset");
    if (@offsetOf(LeafNode, "len") != 248) @compileError("LeafNode.len offset");
    if (@offsetOf(LeafNode, "vals") != 256) @compileError("LeafNode.vals offset");

    if (@sizeOf(InternalNode) != 640) @compileError("InternalNode must be 640 bytes");
    if (@alignOf(InternalNode) != 128) @compileError("InternalNode must be 128-byte aligned");
    if (@offsetOf(InternalNode, "keys") != 0) @compileError("InternalNode.keys offset");
    if (@offsetOf(InternalNode, "len") != 248) @compileError("InternalNode.len offset");
    if (@offsetOf(InternalNode, "children") != 256) @compileError("InternalNode.children offset");
    if (@offsetOf(InternalNode, "vals") != 384) @compileError("InternalNode.vals offset");
}

const PathEntry = struct {
    node: u32,
    pos: u8,
};

/// Branchless, 128-byte-aligned SIMD lower_bound over 31 i64 keys with I64_MAX sentinels.
/// Tests keys[15] < target to select either CL 0 (keys[0..14]) or CL 1 (keys[16..30]),
/// both 15 keys starting on a 128-byte boundary. When keys[15] >= target, CL 1 is never touched.
inline fn lowerBound(keys: *align(128) const [MAX_KEYS]i64, target: i64) usize {
    const right = keys[15] < target;
    const base: usize = if (right) 16 else 0;
    const p: [*]const i64 = @as([*]const i64, @ptrCast(keys)) + base;
    const vt: @Vector(2, i64) = @splat(target);
    const neg_one: @Vector(2, i64) = @splat(-1);
    const zero: @Vector(2, i64) = @splat(0);

    const v0: @Vector(2, i64) = p[0..2].*;
    const v1: @Vector(2, i64) = p[2..4].*;
    const v2: @Vector(2, i64) = p[4..6].*;
    const v3: @Vector(2, i64) = p[6..8].*;
    const v4: @Vector(2, i64) = p[8..10].*;
    const v5: @Vector(2, i64) = p[10..12].*;
    const v6: @Vector(2, i64) = p[12..14].*;

    const s0 = @select(i64, v0 < vt, neg_one, zero) + @select(i64, v1 < vt, neg_one, zero);
    const s1 = @select(i64, v2 < vt, neg_one, zero) + @select(i64, v3 < vt, neg_one, zero);
    const s2 = @select(i64, v4 < vt, neg_one, zero) + @select(i64, v5 < vt, neg_one, zero);
    const s3 = @select(i64, v6 < vt, neg_one, zero);

    const total = (s0 + s1) + (s2 + s3);
    const count: usize = @intCast(-(total[0] + total[1]));
    return base + count + @intFromBool(p[14] < target);
}

/// Fast inline non-overlapping copy for small i64 arrays (up to 31 elements),
/// avoiding libc memcpy call overhead while vectorizing cleanly on ARM64 NEON.
inline fn copyI64(dst: [*]i64, src: [*]const i64, n: usize) void {
    var i: usize = 0;
    while (i + 4 <= n) : (i += 4) {
        const v0: @Vector(2, i64) = src[i..][0..2].*;
        const v1: @Vector(2, i64) = src[i + 2 ..][0..2].*;
        dst[i..][0..2].* = v0;
        dst[i + 2 ..][0..2].* = v1;
    }
    while (i < n) : (i += 1) {
        dst[i] = src[i];
    }
}

inline fn copyU32(dst: [*]u32, src: [*]const u32, n: usize) void {
    var i: usize = 0;
    while (i + 4 <= n) : (i += 4) {
        const v: @Vector(4, u32) = src[i..][0..4].*;
        dst[i..][0..4].* = v;
    }
    while (i < n) : (i += 1) {
        dst[i] = src[i];
    }
}

inline fn shiftRight(comptime Elem: type, arr: [*]Elem, pos: usize, n: usize) void {
    var i: usize = n;
    while (i > pos) : (i -= 1) {
        arr[i] = arr[i - 1];
    }
}

inline fn shiftRightBy(comptime Elem: type, arr: [*]Elem, n: usize, by: usize) void {
    var i: usize = n;
    while (i > 0) {
        i -= 1;
        arr[i + by] = arr[i];
    }
}

inline fn shiftLeft(comptime Elem: type, arr: [*]Elem, pos: usize, n: usize) void {
    var i: usize = pos;
    const end = n - 1;
    while (i < end) : (i += 1) {
        arr[i] = arr[i + 1];
    }
}

inline fn shiftLeftBy(comptime Elem: type, arr: [*]Elem, n: usize, by: usize) void {
    const keep = n - by;
    var i: usize = 0;
    while (i < keep) : (i += 1) {
        arr[i] = arr[i + by];
    }
}

inline fn fillSentinels(keys: *[MAX_KEYS]i64, start: usize) void {
    var i: usize = start;
    while (i < MAX_KEYS) : (i += 1) {
        keys[i] = I64_MAX;
    }
}

inline fn prefetchLeaf(leaf: *const LeafNode) void {
    @prefetch(&leaf.keys[0], .{ .rw = .read, .locality = 1, .cache = .data });
    @prefetch(&leaf.keys[16], .{ .rw = .read, .locality = 1, .cache = .data });
    @prefetch(&leaf.vals[0], .{ .rw = .read, .locality = 1, .cache = .data });
    @prefetch(&leaf.vals[16], .{ .rw = .read, .locality = 1, .cache = .data });
}

pub const BTree = struct {
    allocator: std.mem.Allocator,
    leaves: []LeafNode,
    internals: []InternalNode,
    leaves_len: u32,
    internals_len: u32,
    free_leaf: u32,
    free_internal: u32,
    root: u32,
    tree_height: u8,
    count: usize,

    pub fn init(allocator: std.mem.Allocator) BTree {
        return .{
            .allocator = allocator,
            .leaves = &.{},
            .internals = &.{},
            .leaves_len = 0,
            .internals_len = 0,
            .free_leaf = NULL_REF,
            .free_internal = NULL_REF,
            .root = NULL_REF,
            .tree_height = 0,
            .count = 0,
        };
    }

    pub fn deinit(self: *BTree) void {
        if (self.leaves.len > 0) {
            self.allocator.free(self.leaves);
        }
        if (self.internals.len > 0) {
            self.allocator.free(self.internals);
        }
        self.* = init(self.allocator);
    }

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

    pub fn height(self: *const BTree) usize {
        return self.tree_height;
    }

    // --------------------------------------------------------- pool management

    fn growLeaves(self: *BTree, min_cap: usize) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        var new_cap: usize = if (self.leaves.len == 0) 8 else self.leaves.len;
        while (new_cap < min_cap) {
            new_cap = if (new_cap < 65536) new_cap * 2 else new_cap + (new_cap >> 1);
        }
        self.leaves = if (self.leaves.len == 0)
            try self.allocator.alloc(LeafNode, new_cap)
        else
            try self.allocator.realloc(self.leaves, new_cap);
    }

    fn growInternals(self: *BTree, min_cap: usize) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        var new_cap: usize = if (self.internals.len == 0) 4 else self.internals.len;
        while (new_cap < min_cap) {
            new_cap = if (new_cap < 16384) new_cap * 2 else new_cap + (new_cap >> 1);
        }
        self.internals = if (self.internals.len == 0)
            try self.allocator.alloc(InternalNode, new_cap)
        else
            try self.allocator.realloc(self.internals, new_cap);
    }

    inline fn ensureLeafSlot(self: *BTree) std.mem.Allocator.Error!void {
        if (self.free_leaf == NULL_REF and self.leaves_len == self.leaves.len) {
            try self.growLeaves(@as(usize, self.leaves_len) + 1);
        }
    }

    inline fn ensureInternalSlots(self: *BTree, needed: usize) std.mem.Allocator.Error!void {
        if (@as(usize, self.internals_len) + needed > self.internals.len) {
            try self.growInternals(@as(usize, self.internals_len) + needed);
        }
    }

    inline fn allocLeafNoFail(self: *BTree) u32 {
        if (self.free_leaf != NULL_REF) {
            const idx = self.free_leaf;
            self.free_leaf = @bitCast(@as(i32, @truncate(self.leaves.ptr[idx].keys[0])));
            return idx;
        }
        const idx = self.leaves_len;
        self.leaves_len = idx + 1;
        return idx;
    }

    inline fn freeLeaf(self: *BTree, idx: u32) void {
        self.leaves.ptr[idx].keys[0] = @as(i64, @as(i32, @bitCast(self.free_leaf)));
        self.free_leaf = idx;
    }

    inline fn allocInternalNoFail(self: *BTree) u32 {
        if (self.free_internal != NULL_REF) {
            const idx = self.free_internal;
            self.free_internal = @bitCast(@as(i32, @truncate(self.internals.ptr[idx].keys[0])));
            return idx;
        }
        const idx = self.internals_len;
        self.internals_len = idx + 1;
        return idx;
    }

    inline fn freeInternal(self: *BTree, idx: u32) void {
        self.internals.ptr[idx].keys[0] = @as(i64, @as(i32, @bitCast(self.free_internal)));
        self.free_internal = idx;
    }

    // --------------------------------------------------------------------- get

    pub fn get(self: *const BTree, key: i64) ?i64 {
        const h = self.tree_height;
        if (h == 0) {
            @branchHint(.unlikely);
            return null;
        }
        var node_idx = self.root;
        var levels_below: usize = h - 1;
        const internals = self.internals.ptr;
        while (levels_below > 0) : (levels_below -= 1) {
            const node = &internals[node_idx];
            const pos = lowerBound(&node.keys, key);
            if (pos < MAX_KEYS and node.keys[pos] == key) {
                @branchHint(.unlikely);
                if (pos < node.len) return node.vals[pos];
            }
            node_idx = node.children[pos];
        }
        const leaf = &self.leaves.ptr[node_idx];
        const pos = lowerBound(&leaf.keys, key);
        if (pos < MAX_KEYS and leaf.keys[pos] == key and pos < leaf.len) {
            return leaf.vals[pos];
        }
        return null;
    }

    // ------------------------------------------------------------------ insert

    pub fn insert(self: *BTree, key: i64, value: i64) std.mem.Allocator.Error!bool {
        const h = self.tree_height;
        if (h == 0) {
            @branchHint(.unlikely);
            try self.ensureLeafSlot();
            const idx = self.allocLeafNoFail();
            const leaf = &self.leaves.ptr[idx];
            leaf.keys[0] = key;
            fillSentinels(&leaf.keys, 1);
            leaf.vals[0] = value;
            leaf.len = 1;
            self.root = idx;
            self.tree_height = 1;
            self.count = 1;
            return true;
        }

        var path: [MAX_HEIGHT]PathEntry = undefined;
        var node_idx = self.root;
        var depth: usize = 0;
        const leaf_depth: usize = h - 1;
        const internals = self.internals.ptr;

        while (depth < leaf_depth) : (depth += 1) {
            const node = &internals[node_idx];
            const pos = lowerBound(&node.keys, key);
            if (pos < MAX_KEYS and node.keys[pos] == key) {
                @branchHint(.unlikely);
                if (pos < node.len) {
                    node.vals[pos] = value;
                    return false;
                }
            }
            path[depth] = .{ .node = node_idx, .pos = @intCast(pos) };
            node_idx = node.children[pos];
        }

        const leaf = &self.leaves.ptr[node_idx];
        const leaf_len: usize = leaf.len;

        // Fast path for sequential/rightmost append
        if (leaf_len > 0 and key > leaf.keys[leaf_len - 1]) {
            if (leaf_len < MAX_KEYS) {
                leaf.keys[leaf_len] = key;
                leaf.vals[leaf_len] = value;
                leaf.len = @intCast(leaf_len + 1);
                self.count += 1;
                return true;
            }
            try self.splitAndPropagate(node_idx, leaf_len, key, value, &path, leaf_depth);
            self.count += 1;
            return true;
        }

        const pos = lowerBound(&leaf.keys, key);
        if (pos < MAX_KEYS and leaf.keys[pos] == key and pos < leaf_len) {
            leaf.vals[pos] = value;
            return false;
        }

        if (leaf_len < MAX_KEYS) {
            shiftRight(i64, &leaf.keys, pos, leaf_len);
            shiftRight(i64, &leaf.vals, pos, leaf_len);
            leaf.keys[pos] = key;
            leaf.vals[pos] = value;
            leaf.len = @intCast(leaf_len + 1);
            self.count += 1;
            return true;
        }

        try self.splitAndPropagate(node_idx, pos, key, value, &path, leaf_depth);
        self.count += 1;
        return true;
    }

    fn splitAndPropagate(
        self: *BTree,
        leaf_idx: u32,
        ins_pos: usize,
        ins_key: i64,
        ins_val: i64,
        path: *const [MAX_HEIGHT]PathEntry,
        leaf_depth: usize,
    ) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        // Reserve all worst-case memory upfront so pools cannot reallocate mid-split.
        try self.ensureLeafSlot();
        try self.ensureInternalSlots(leaf_depth + 1);

        const right_leaf_idx = self.allocLeafNoFail();
        const left = &self.leaves.ptr[leaf_idx];
        const right = &self.leaves.ptr[right_leaf_idx];

        var prom_key: i64 = undefined;
        var prom_val: i64 = undefined;
        var prom_right: u32 = right_leaf_idx;

        // Split 31 existing keys + 1 new key = 32 keys into left + median + right.
        if (ins_pos < 15) {
            // Left: 15 keys (old[0..ins_pos], ins, old[ins_pos..14])
            // Median: old[14]
            // Right: 16 keys (old[15..31])
            prom_key = left.keys[14];
            prom_val = left.vals[14];
            copyI64(&right.keys, left.keys[15..].ptr, 16);
            copyI64(&right.vals, left.vals[15..].ptr, 16);
            fillSentinels(&right.keys, 16);
            right.len = 16;

            shiftRight(i64, &left.keys, ins_pos, 14);
            shiftRight(i64, &left.vals, ins_pos, 14);
            left.keys[ins_pos] = ins_key;
            left.vals[ins_pos] = ins_val;
            fillSentinels(&left.keys, 15);
            left.len = 15;
        } else if (ins_pos == 15) {
            // Left: 15 keys (old[0..15]), Median: ins, Right: 16 keys (old[15..31])
            prom_key = ins_key;
            prom_val = ins_val;
            copyI64(&right.keys, left.keys[15..].ptr, 16);
            copyI64(&right.vals, left.vals[15..].ptr, 16);
            fillSentinels(&right.keys, 16);
            right.len = 16;

            fillSentinels(&left.keys, 15);
            left.len = 15;
        } else if (ins_pos == 16) {
            // Left: 16 keys (old[0..16]), Median: ins, Right: 15 keys (old[16..31])
            prom_key = ins_key;
            prom_val = ins_val;
            copyI64(&right.keys, left.keys[16..].ptr, 15);
            copyI64(&right.vals, left.vals[16..].ptr, 15);
            fillSentinels(&right.keys, 15);
            right.len = 15;

            fillSentinels(&left.keys, 16);
            left.len = 16;
        } else {
            // ins_pos in 17..31
            // Left: 16 keys (old[0..16]), Median: old[16]
            // Right: 15 keys (old[17..ins_pos], ins, old[ins_pos..31])
            prom_key = left.keys[16];
            prom_val = left.vals[16];
            const pre = ins_pos - 17;
            const post = MAX_KEYS - ins_pos;
            copyI64(&right.keys, left.keys[17..].ptr, pre);
            copyI64(&right.vals, left.vals[17..].ptr, pre);
            right.keys[pre] = ins_key;
            right.vals[pre] = ins_val;
            if (post > 0) {
                copyI64(right.keys[pre + 1 ..].ptr, left.keys[ins_pos..].ptr, post);
                copyI64(right.vals[pre + 1 ..].ptr, left.vals[ins_pos..].ptr, post);
            }
            fillSentinels(&right.keys, 15);
            right.len = 15;

            fillSentinels(&left.keys, 16);
            left.len = 16;
        }

        // Propagate promoted (prom_key, prom_val, prom_right) up internal levels.
        const internals = self.internals.ptr;
        var d: usize = leaf_depth;
        while (d > 0) {
            d -= 1;
            const entry = path[d];
            const p = &internals[entry.node];
            const p_len: usize = p.len;
            const pos: usize = entry.pos;

            if (p_len < MAX_KEYS) {
                shiftRight(i64, &p.keys, pos, p_len);
                shiftRight(i64, &p.vals, pos, p_len);
                shiftRight(u32, &p.children, pos + 1, p_len + 1);
                p.keys[pos] = prom_key;
                p.vals[pos] = prom_val;
                p.children[pos + 1] = prom_right;
                p.len = @intCast(p_len + 1);
                return;
            }

            // Internal node is full (31 keys, 32 children); split it.
            const right_int_idx = self.allocInternalNoFail();
            const r = &internals[right_int_idx];

            const new_k = prom_key;
            const new_v = prom_val;
            const new_c = prom_right;

            if (pos < 15) {
                // Left: 15 keys, 16 children; Median: old[14]; Right: 16 keys, 17 children
                prom_key = p.keys[14];
                prom_val = p.vals[14];
                copyI64(&r.keys, p.keys[15..].ptr, 16);
                copyI64(&r.vals, p.vals[15..].ptr, 16);
                copyU32(&r.children, p.children[15..].ptr, 17);
                fillSentinels(&r.keys, 16);
                r.len = 16;

                shiftRight(i64, &p.keys, pos, 14);
                shiftRight(i64, &p.vals, pos, 14);
                shiftRight(u32, &p.children, pos + 1, 15);
                p.keys[pos] = new_k;
                p.vals[pos] = new_v;
                p.children[pos + 1] = new_c;
                fillSentinels(&p.keys, 15);
                p.len = 15;
            } else if (pos == 15) {
                // Left: 15 keys, 16 children; Median: new; Right: 16 keys, 17 children
                prom_key = new_k;
                prom_val = new_v;
                copyI64(&r.keys, p.keys[15..].ptr, 16);
                copyI64(&r.vals, p.vals[15..].ptr, 16);
                r.children[0] = new_c;
                copyU32(r.children[1..].ptr, p.children[16..].ptr, 16);
                fillSentinels(&r.keys, 16);
                r.len = 16;

                fillSentinels(&p.keys, 15);
                p.len = 15;
            } else if (pos == 16) {
                // Left: 16 keys, 17 children; Median: new; Right: 15 keys, 16 children
                prom_key = new_k;
                prom_val = new_v;
                copyI64(&r.keys, p.keys[16..].ptr, 15);
                copyI64(&r.vals, p.vals[16..].ptr, 15);
                r.children[0] = new_c;
                copyU32(r.children[1..].ptr, p.children[17..].ptr, 15);
                fillSentinels(&r.keys, 15);
                r.len = 15;

                fillSentinels(&p.keys, 16);
                p.len = 16;
            } else {
                // pos in 17..31
                // Left: 16 keys, 17 children; Median: old[16]; Right: 15 keys, 16 children
                prom_key = p.keys[16];
                prom_val = p.vals[16];
                const pre = pos - 17;
                const post = MAX_KEYS - pos;
                copyI64(&r.keys, p.keys[17..].ptr, pre);
                copyI64(&r.vals, p.vals[17..].ptr, pre);
                r.keys[pre] = new_k;
                r.vals[pre] = new_v;
                if (post > 0) {
                    copyI64(r.keys[pre + 1 ..].ptr, p.keys[pos..].ptr, post);
                    copyI64(r.vals[pre + 1 ..].ptr, p.vals[pos..].ptr, post);
                }
                const c_pre = pos - 16; // = pre + 1
                const c_post = MAX_KEYS - pos; // = post
                copyU32(&r.children, p.children[17..].ptr, c_pre);
                r.children[c_pre] = new_c;
                if (c_post > 0) {
                    copyU32(r.children[c_pre + 1 ..].ptr, p.children[pos + 1 ..].ptr, c_post);
                }
                fillSentinels(&r.keys, 15);
                r.len = 15;

                fillSentinels(&p.keys, 16);
                p.len = 16;
            }

            prom_right = right_int_idx;
        }

        // Root split: create a new root internal node.
        const new_root_idx = self.allocInternalNoFail();
        const new_root = &internals[new_root_idx];
        new_root.keys[0] = prom_key;
        fillSentinels(&new_root.keys, 1);
        new_root.vals[0] = prom_val;
        new_root.children[0] = self.root;
        new_root.children[1] = prom_right;
        new_root.len = 1;
        self.root = new_root_idx;
        self.tree_height += 1;
    }

    // ------------------------------------------------------------------ remove

    pub fn remove(self: *BTree, key: i64) bool {
        const h = self.tree_height;
        if (h == 0) {
            @branchHint(.unlikely);
            return false;
        }

        var path: [MAX_HEIGHT]PathEntry = undefined;
        var node_idx = self.root;
        var depth: usize = 0;
        const leaf_depth: usize = h - 1;
        const internals = self.internals.ptr;

        while (depth < leaf_depth) : (depth += 1) {
            const node = &internals[node_idx];
            const pos = lowerBound(&node.keys, key);
            if (pos < MAX_KEYS and node.keys[pos] == key) {
                @branchHint(.unlikely);
                if (pos < node.len) {
                    // Found in internal node: replace with in-order predecessor from leaf.
                    path[depth] = .{ .node = node_idx, .pos = @intCast(pos) };
                    var cur = node.children[pos];
                    var d = depth + 1;
                    while (d < leaf_depth) : (d += 1) {
                        const cn = &internals[cur];
                        const last_c: usize = cn.len;
                        path[d] = .{ .node = cur, .pos = @intCast(last_c) };
                        cur = cn.children[last_c];
                    }
                    const pred_leaf = &self.leaves.ptr[cur];
                    const last: usize = pred_leaf.len - 1;
                    node.keys[pos] = pred_leaf.keys[last];
                    node.vals[pos] = pred_leaf.vals[last];
                    pred_leaf.keys[last] = I64_MAX;
                    pred_leaf.len = @intCast(last);
                    self.count -= 1;
                    if (last < MIN_KEYS) {
                        self.rebalanceFromLeaf(cur, &path, leaf_depth);
                    }
                    return true;
                }
            }
            path[depth] = .{ .node = node_idx, .pos = @intCast(pos) };
            node_idx = node.children[pos];
        }

        const leaf = &self.leaves.ptr[node_idx];
        const pos = lowerBound(&leaf.keys, key);
        const leaf_len: usize = leaf.len;
        if (pos >= MAX_KEYS or leaf.keys[pos] != key or pos >= leaf_len) {
            return false;
        }

        shiftLeft(i64, &leaf.keys, pos, leaf_len);
        shiftLeft(i64, &leaf.vals, pos, leaf_len);
        const new_len = leaf_len - 1;
        leaf.keys[new_len] = I64_MAX;
        leaf.len = @intCast(new_len);
        self.count -= 1;

        if (leaf_depth == 0) {
            if (new_len == 0) {
                self.freeLeaf(node_idx);
                self.root = NULL_REF;
                self.tree_height = 0;
            }
            return true;
        }

        if (new_len < MIN_KEYS) {
            self.rebalanceFromLeaf(node_idx, &path, leaf_depth);
        }
        return true;
    }

    fn rebalanceFromLeaf(
        self: *BTree,
        leaf_idx: u32,
        path: *const [MAX_HEIGHT]PathEntry,
        leaf_depth: usize,
    ) void {
        @branchHint(.cold);
        const internals = self.internals.ptr;
        const leaves = self.leaves.ptr;
        const parent_entry = path[leaf_depth - 1];
        const parent = &internals[parent_entry.node];
        const ci: usize = parent_entry.pos;
        const p_len: usize = parent.len;
        const cur = &leaves[leaf_idx]; // has MIN_KEYS - 1 = 14 keys

        // Try redistributing from left sibling
        if (ci > 0) {
            const left = &leaves[parent.children[ci - 1]];
            const l_len: usize = left.len;
            if (l_len > MIN_KEYS) {
                const shift: usize = (l_len - (MIN_KEYS - 1)) >> 1; // >= 1
                const cur_len: usize = MIN_KEYS - 1;
                shiftRightBy(i64, &cur.keys, cur_len, shift);
                shiftRightBy(i64, &cur.vals, cur_len, shift);
                cur.keys[shift - 1] = parent.keys[ci - 1];
                cur.vals[shift - 1] = parent.vals[ci - 1];
                const move_from_left = shift - 1;
                if (move_from_left > 0) {
                    const src_start = l_len - move_from_left;
                    copyI64(&cur.keys, left.keys[src_start..].ptr, move_from_left);
                    copyI64(&cur.vals, left.vals[src_start..].ptr, move_from_left);
                }
                const new_l_len = l_len - shift;
                parent.keys[ci - 1] = left.keys[new_l_len];
                parent.vals[ci - 1] = left.vals[new_l_len];
                var j = new_l_len;
                while (j < l_len) : (j += 1) left.keys[j] = I64_MAX;
                left.len = @intCast(new_l_len);
                cur.len = @intCast(cur_len + shift);
                return;
            }
        }

        // Try redistributing from right sibling
        if (ci < p_len) {
            const right = &leaves[parent.children[ci + 1]];
            const r_len: usize = right.len;
            if (r_len > MIN_KEYS) {
                const shift: usize = (r_len - (MIN_KEYS - 1)) >> 1; // >= 1
                const cur_len: usize = MIN_KEYS - 1;
                cur.keys[cur_len] = parent.keys[ci];
                cur.vals[cur_len] = parent.vals[ci];
                const move_from_right = shift - 1;
                if (move_from_right > 0) {
                    copyI64(cur.keys[cur_len + 1 ..].ptr, &right.keys, move_from_right);
                    copyI64(cur.vals[cur_len + 1 ..].ptr, &right.vals, move_from_right);
                }
                parent.keys[ci] = right.keys[shift - 1];
                parent.vals[ci] = right.vals[shift - 1];
                shiftLeftBy(i64, &right.keys, r_len, shift);
                shiftLeftBy(i64, &right.vals, r_len, shift);
                const new_r_len = r_len - shift;
                var j = new_r_len;
                while (j < r_len) : (j += 1) right.keys[j] = I64_MAX;
                right.len = @intCast(new_r_len);
                cur.len = @intCast(cur_len + shift);
                return;
            }
        }

        // Must merge two leaves
        const sep_idx: usize = if (ci > 0) ci - 1 else 0;
        const left_idx = parent.children[sep_idx];
        const right_idx = parent.children[sep_idx + 1];
        const left = &leaves[left_idx];
        const right = &leaves[right_idx];
        const l_len: usize = left.len;
        const r_len: usize = right.len;

        left.keys[l_len] = parent.keys[sep_idx];
        left.vals[l_len] = parent.vals[sep_idx];
        copyI64(left.keys[l_len + 1 ..].ptr, &right.keys, r_len);
        copyI64(left.vals[l_len + 1 ..].ptr, &right.vals, r_len);
        left.len = @intCast(l_len + 1 + r_len);
        self.freeLeaf(right_idx);

        // Remove separator and right child from parent
        shiftLeft(i64, &parent.keys, sep_idx, p_len);
        shiftLeft(i64, &parent.vals, sep_idx, p_len);
        shiftLeft(u32, &parent.children, sep_idx + 1, p_len + 1);
        const new_p_len = p_len - 1;
        parent.keys[new_p_len] = I64_MAX;
        parent.len = @intCast(new_p_len);

        // Propagate underflow up internal nodes
        var d: usize = leaf_depth - 1;
        while (true) {
            const node_idx = path[d].node;
            const node = &internals[node_idx];
            const n_len: usize = node.len;

            if (d == 0) {
                if (n_len == 0) {
                    const sole_child = node.children[0];
                    self.freeInternal(node_idx);
                    self.root = sole_child;
                    self.tree_height -= 1;
                }
                return;
            }

            if (n_len >= MIN_KEYS) return;

            // Internal node `node` has MIN_KEYS - 1 = 14 keys; rebalance via its parent.
            const p_entry = path[d - 1];
            const par = &internals[p_entry.node];
            const pci: usize = p_entry.pos;
            const par_len: usize = par.len;

            // Try redistributing from left internal sibling
            if (pci > 0) {
                const l_sib = &internals[par.children[pci - 1]];
                const ls_len: usize = l_sib.len;
                if (ls_len > MIN_KEYS) {
                    const shift: usize = (ls_len - (MIN_KEYS - 1)) >> 1;
                    shiftRightBy(i64, &node.keys, n_len, shift);
                    shiftRightBy(i64, &node.vals, n_len, shift);
                    shiftRightBy(u32, &node.children, n_len + 1, shift);

                    node.keys[shift - 1] = par.keys[pci - 1];
                    node.vals[shift - 1] = par.vals[pci - 1];
                    const move_k = shift - 1;
                    if (move_k > 0) {
                        const ks = ls_len - move_k;
                        copyI64(&node.keys, l_sib.keys[ks..].ptr, move_k);
                        copyI64(&node.vals, l_sib.vals[ks..].ptr, move_k);
                    }
                    const cs = ls_len + 1 - shift;
                    copyU32(&node.children, l_sib.children[cs..].ptr, shift);

                    const new_ls_len = ls_len - shift;
                    par.keys[pci - 1] = l_sib.keys[new_ls_len];
                    par.vals[pci - 1] = l_sib.vals[new_ls_len];
                    var j = new_ls_len;
                    while (j < ls_len) : (j += 1) l_sib.keys[j] = I64_MAX;
                    l_sib.len = @intCast(new_ls_len);
                    node.len = @intCast(n_len + shift);
                    return;
                }
            }

            // Try redistributing from right internal sibling
            if (pci < par_len) {
                const r_sib = &internals[par.children[pci + 1]];
                const rs_len: usize = r_sib.len;
                if (rs_len > MIN_KEYS) {
                    const shift: usize = (rs_len - (MIN_KEYS - 1)) >> 1;
                    node.keys[n_len] = par.keys[pci];
                    node.vals[n_len] = par.vals[pci];
                    const move_k = shift - 1;
                    if (move_k > 0) {
                        copyI64(node.keys[n_len + 1 ..].ptr, &r_sib.keys, move_k);
                        copyI64(node.vals[n_len + 1 ..].ptr, &r_sib.vals, move_k);
                    }
                    copyU32(node.children[n_len + 1 ..].ptr, &r_sib.children, shift);

                    par.keys[pci] = r_sib.keys[shift - 1];
                    par.vals[pci] = r_sib.vals[shift - 1];
                    shiftLeftBy(i64, &r_sib.keys, rs_len, shift);
                    shiftLeftBy(i64, &r_sib.vals, rs_len, shift);
                    shiftLeftBy(u32, &r_sib.children, rs_len + 1, shift);

                    const new_rs_len = rs_len - shift;
                    var j = new_rs_len;
                    while (j < rs_len) : (j += 1) r_sib.keys[j] = I64_MAX;
                    r_sib.len = @intCast(new_rs_len);
                    node.len = @intCast(n_len + shift);
                    return;
                }
            }

            // Merge internal nodes
            const isep: usize = if (pci > 0) pci - 1 else 0;
            const li = par.children[isep];
            const ri = par.children[isep + 1];
            const ln = &internals[li];
            const rn = &internals[ri];
            const ln_len: usize = ln.len;
            const rn_len: usize = rn.len;

            ln.keys[ln_len] = par.keys[isep];
            ln.vals[ln_len] = par.vals[isep];
            copyI64(ln.keys[ln_len + 1 ..].ptr, &rn.keys, rn_len);
            copyI64(ln.vals[ln_len + 1 ..].ptr, &rn.vals, rn_len);
            copyU32(ln.children[ln_len + 1 ..].ptr, &rn.children, rn_len + 1);
            ln.len = @intCast(ln_len + 1 + rn_len);
            self.freeInternal(ri);

            shiftLeft(i64, &par.keys, isep, par_len);
            shiftLeft(i64, &par.vals, isep, par_len);
            shiftLeft(u32, &par.children, isep + 1, par_len + 1);
            const new_par_len = par_len - 1;
            par.keys[new_par_len] = I64_MAX;
            par.len = @intCast(new_par_len);

            d -= 1;
        }
    }

    // ------------------------------------------------------------------- range

    pub fn range(self: *const BTree, lo: i64, hi: i64, out_keys: []i64, out_vals: []i64) usize {
        const limit = out_keys.len;
        const h = self.tree_height;
        if (h == 0 or lo > hi or limit == 0) {
            return 0;
        }

        const leaves = self.leaves.ptr;
        if (h == 1) {
            const leaf = &leaves[self.root];
            const n: usize = leaf.len;
            const start = lowerBound(&leaf.keys, lo);
            if (start >= n) return 0;
            const end: usize = if (leaf.keys[n - 1] <= hi) n else lowerBound(&leaf.keys, hi + 1);
            if (end <= start) return 0;
            const take = @min(end - start, limit);
            copyI64(out_keys.ptr, leaf.keys[start..].ptr, take);
            copyI64(out_vals.ptr, leaf.vals[start..].ptr, take);
            return take;
        }

        const internals = self.internals.ptr;
        var stack: [MAX_HEIGHT]PathEntry = undefined;
        const leaf_parent_depth: usize = h - 2;
        var written: usize = 0;

        // Descend from root to lo, stopping early if lo hits an internal node directly.
        var cur: u32 = self.root;
        var d: usize = 0;
        var hit_internal = false;
        while (d <= leaf_parent_depth) : (d += 1) {
            const node = &internals[cur];
            const pos = lowerBound(&node.keys, lo);
            stack[d] = .{ .node = cur, .pos = @intCast(pos) };
            if (pos < MAX_KEYS and node.keys[pos] == lo and pos < node.len) {
                // Exact hit of `lo` in internal node at depth `d`!
                out_keys[0] = lo;
                out_vals[0] = node.vals[pos];
                written = 1;
                if (limit == 1) return 1;
                stack[d].pos = @intCast(pos + 1);
                if (d < leaf_parent_depth) {
                    var next_node = node.children[pos + 1];
                    var dd = d + 1;
                    while (dd < leaf_parent_depth) : (dd += 1) {
                        stack[dd] = .{ .node = next_node, .pos = 0 };
                        next_node = internals[next_node].children[0];
                    }
                    stack[leaf_parent_depth] = .{ .node = next_node, .pos = 0 };
                }
                hit_internal = true;
                break;
            }
            cur = node.children[pos];
        }

        if (!hit_internal) {
            // Scan the first leaf starting at lowerBound(lo)
            const first_leaf = &leaves[cur];
            const fn_len: usize = first_leaf.len;
            const start = lowerBound(&first_leaf.keys, lo);
            if (start < fn_len) {
                if (first_leaf.keys[fn_len - 1] <= hi) {
                    const avail = fn_len - start;
                    const take = @min(avail, limit);
                    copyI64(out_keys.ptr, first_leaf.keys[start..].ptr, take);
                    copyI64(out_vals.ptr, first_leaf.vals[start..].ptr, take);
                    written = take;
                    if (written == limit) return written;
                } else {
                    const end = lowerBound(&first_leaf.keys, hi + 1);
                    if (end <= start) return 0;
                    const take = @min(end - start, limit);
                    copyI64(out_keys.ptr, first_leaf.keys[start..].ptr, take);
                    copyI64(out_vals.ptr, first_leaf.vals[start..].ptr, take);
                    return take;
                }
            }

            // Advance past first leaf in its leaf-parent
            const parent = &internals[stack[leaf_parent_depth].node];
            const pos: usize = stack[leaf_parent_depth].pos;
            const p_len: usize = parent.len;
            if (pos < p_len) {
                const pk = parent.keys[pos];
                if (pk > hi) return written;
                out_keys[written] = pk;
                out_vals[written] = parent.vals[pos];
                written += 1;
                if (written == limit) return written;
                stack[leaf_parent_depth].pos = @intCast(pos + 1);
            } else {
                stack[leaf_parent_depth].pos = @intCast(p_len + 1);
            }
        }

        // Main in-order scan loop: tight inner loop over leaf-parent + software prefetching.
        while (true) {
            const parent = &internals[stack[leaf_parent_depth].node];
            const p_len: usize = parent.len;
            var i: usize = stack[leaf_parent_depth].pos;

            if (i <= p_len) {
                // Prime prefetch pipeline for upcoming sibling leaves
                if (i < p_len and parent.keys[i] <= hi and limit - written > 15) {
                    prefetchLeaf(&leaves[parent.children[i + 1]]);
                    if (i + 1 < p_len and parent.keys[i + 1] <= hi and limit - written > 30) {
                        prefetchLeaf(&leaves[parent.children[i + 2]]);
                        if (i + 2 < p_len and parent.keys[i + 2] <= hi and limit - written > 45) {
                            prefetchLeaf(&leaves[parent.children[i + 3]]);
                        }
                    }
                }

                while (true) {
                    if (i + 4 <= p_len and parent.keys[i + 3] <= hi and limit - written > 60) {
                        prefetchLeaf(&leaves[parent.children[i + 4]]);
                    }

                    const leaf = &leaves[parent.children[i]];
                    const n: usize = leaf.len;
                    const rem = limit - written;
                    if (leaf.keys[n - 1] <= hi and n <= rem) {
                        copyI64(out_keys.ptr + written, &leaf.keys, n);
                        copyI64(out_vals.ptr + written, &leaf.vals, n);
                        written += n;
                        if (written == limit) return written;
                    } else {
                        const end: usize = if (leaf.keys[n - 1] > hi) lowerBound(&leaf.keys, hi + 1) else n;
                        const take = @min(end, rem);
                        if (take > 0) {
                            copyI64(out_keys.ptr + written, &leaf.keys, take);
                            copyI64(out_vals.ptr + written, &leaf.vals, take);
                        }
                        return written + take;
                    }

                    if (i == p_len) break;

                    const pk = parent.keys[i];
                    if (pk > hi) return written;
                    out_keys[written] = pk;
                    out_vals[written] = parent.vals[i];
                    written += 1;
                    if (written == limit) return written;
                    i += 1;
                }
            }

            // Unwind up the stack to find the next ancestor with remaining keys/children.
            var up: usize = leaf_parent_depth;
            while (true) {
                if (up == 0) return written;
                up -= 1;
                const anc = &internals[stack[up].node];
                const ap: usize = stack[up].pos;
                if (ap < anc.len) {
                    const ak = anc.keys[ap];
                    if (ak > hi) return written;
                    out_keys[written] = ak;
                    out_vals[written] = anc.vals[ap];
                    written += 1;
                    if (written == limit) return written;
                    stack[up].pos = @intCast(ap + 1);

                    var next_node = anc.children[ap + 1];
                    var dd = up + 1;
                    while (dd < leaf_parent_depth) : (dd += 1) {
                        stack[dd] = .{ .node = next_node, .pos = 0 };
                        next_node = internals[next_node].children[0];
                    }
                    stack[leaf_parent_depth] = .{ .node = next_node, .pos = 0 };
                    break;
                }
            }
        }
    }
};
