package btree

import (
	"math"
	"unsafe"
)

const (
	minDegree   = 16
	minKeys     = minDegree - 1   // 15
	maxKeys     = 2*minDegree - 1 // 31
	maxChildren = 2 * minDegree   // 32

	leafChunkShift = 9
	leafChunkSize  = 1 << leafChunkShift // 512 leaves = 256 KB per chunk
	leafChunkMask  = leafChunkSize - 1
)

// leafNode is 512 bytes (4 x 128-byte cache lines on Apple M3).
// keys[0..15] occupy CL0 (bytes 0..127); keys[16..30] and count occupy CL1 (bytes 128..255).
// vals[0..30] occupy CL2..CL3 (bytes 256..511), on the same 16 KB page as keys.
// Unused key slots [count..30] are always math.MaxInt64 so branchless search needs no count load.
type leafNode struct {
	keys  [maxKeys]int64
	count uint8
	_     [7]byte
	vals  [maxKeys]int64
	_     int64
}

type leafChunk [leafChunkSize]leafNode

// internalNode is 640 bytes (5 x 128-byte cache lines on Apple M3).
// keys[0..15] occupy CL0 (bytes 0..127); keys[16..30] and count occupy CL1 (bytes 128..255).
// children[0..31] occupy CL2 (bytes 256..383, exactly one cache line).
// vals[0..30] occupy CL3..CL4 (bytes 384..639), untouched during normal descent.
type internalNode struct {
	keys     [maxKeys]int64
	count    uint8
	_        [7]byte
	children [maxChildren]uint32
	vals     [maxKeys]int64
	_        int64
}

// Compile-time struct size assertions.
var (
	_ [512 - unsafe.Sizeof(leafNode{})]byte
	_ [unsafe.Sizeof(leafNode{}) - 512]byte
	_ [640 - unsafe.Sizeof(internalNode{})]byte
	_ [unsafe.Sizeof(internalNode{}) - 640]byte
)

var sentinelKeys = [maxKeys]int64{
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64, math.MaxInt64,
	math.MaxInt64, math.MaxInt64, math.MaxInt64,
}

// BTree is a classic in-memory B-tree of minimum degree t = 16 mapping int64 to int64.
// Leaf and internal nodes are stored in separate pointer-free (noscan) pools indexed by uint32.
type BTree struct {
	root          uint32
	height        int
	length        int
	leafChunks    []*leafChunk
	numLeaves     uint32
	freeLeaves    []uint32
	internals     []internalNode
	freeInternals []uint32
}

type pathEntry struct {
	id  uint32
	idx uint8
}

// New creates an empty B-tree.
func New() *BTree {
	return &BTree{}
}

// Len returns the number of entries in the tree.
func (t *BTree) Len() int {
	return t.length
}

// Height returns the number of levels in the tree (0 when empty).
func (t *BTree) Height() int {
	return t.height
}

func (t *BTree) leafAt(id uint32) *leafNode {
	chunk := *(**leafChunk)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(t.leafChunks)), uintptr(id>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
	return &chunk[id&leafChunkMask]
}

func (t *BTree) allocLeaf() uint32 {
	if n := len(t.freeLeaves); n > 0 {
		id := t.freeLeaves[n-1]
		t.freeLeaves = t.freeLeaves[:n-1]
		return id
	}
	id := t.numLeaves
	t.numLeaves++
	if int(id>>leafChunkShift) >= len(t.leafChunks) {
		t.leafChunks = append(t.leafChunks, new(leafChunk))
	}
	return id
}

func (t *BTree) freeLeaf(id uint32) {
	t.freeLeaves = append(t.freeLeaves, id)
}

func (t *BTree) allocInternal() uint32 {
	if n := len(t.freeInternals); n > 0 {
		id := t.freeInternals[n-1]
		t.freeInternals = t.freeInternals[:n-1]
		return id
	}
	n := len(t.internals)
	if n == cap(t.internals) {
		newCap := cap(t.internals) * 2
		if newCap < 16 {
			newCap = 16
		}
		grown := make([]internalNode, n+1, newCap)
		copy(grown, t.internals)
		t.internals = grown
	} else {
		t.internals = t.internals[:n+1]
	}
	return uint32(n)
}

func (t *BTree) freeInternal(id uint32) {
	t.freeInternals = append(t.freeInternals, id)
}

// Get returns the value stored for key, or (0, false) if absent.
func (t *BTree) Get(key int64) (int64, bool) {
	h := t.height
	if h == 0 {
		return 0, false
	}
	id := t.root
	if h > 1 {
		internalsBase := unsafe.Pointer(unsafe.SliceData(t.internals))
		for lvl := h; lvl > 1; lvl-- {
			n := (*internalNode)(unsafe.Add(internalsBase, uintptr(id)*640))
			base := unsafe.Pointer(&n.keys[0])
			var off uintptr
			if *(*int64)(unsafe.Add(base, 15*8)) < key {
				off = 16 * 8
			}
			if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
				off = next
			}
			if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
				off = next
			}
			if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
				off = next
			}
			if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
				off = next
			}
			if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || int(off>>3) < int(n.count)) {
				return *(*int64)(unsafe.Add(unsafe.Pointer(&n.vals[0]), off)), true
			}
			id = *(*uint32)(unsafe.Add(unsafe.Pointer(&n.children[0]), off>>1))
		}
	}
	chunk := *(**leafChunk)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(t.leafChunks)), uintptr(id>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
	leaf := &chunk[id&leafChunkMask]
	base := unsafe.Pointer(&leaf.keys[0])
	var off uintptr
	if *(*int64)(unsafe.Add(base, 15*8)) < key {
		off = 16 * 8
	}
	if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
		off = next
	}
	if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
		off = next
	}
	if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
		off = next
	}
	if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
		off = next
	}
	if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || int(off>>3) < int(leaf.count)) {
		return *(*int64)(unsafe.Add(unsafe.Pointer(&leaf.vals[0]), off)), true
	}
	return 0, false
}

// Insert inserts (key, value) and returns true if key was absent,
// or replaces its value and returns false if key was already present.
func (t *BTree) Insert(key, value int64) bool {
	h := t.height
	if h == 0 {
		id := t.allocLeaf()
		leaf := t.leafAt(id)
		leaf.keys = sentinelKeys
		leaf.keys[0] = key
		leaf.vals[0] = value
		leaf.count = 1
		t.root = id
		t.height = 1
		t.length = 1
		return true
	}

	var stack [16]pathEntry
	depth := 0
	id := t.root
	if h > 1 {
		internalsBase := unsafe.Pointer(unsafe.SliceData(t.internals))
		for lvl := h; lvl > 1; lvl-- {
			n := (*internalNode)(unsafe.Add(internalsBase, uintptr(id)*640))
			base := unsafe.Pointer(&n.keys[0])
			var off uintptr
			if *(*int64)(unsafe.Add(base, 15*8)) < key {
				off = 16 * 8
			}
			if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
				off = next
			}
			if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
				off = next
			}
			if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
				off = next
			}
			if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
				off = next
			}
			if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || int(off>>3) < int(n.count)) {
				*(*int64)(unsafe.Add(unsafe.Pointer(&n.vals[0]), off)) = value
				return false
			}
			stack[depth] = pathEntry{id: id, idx: uint8(off >> 3)}
			depth++
			id = *(*uint32)(unsafe.Add(unsafe.Pointer(&n.children[0]), off>>1))
		}
	}

	leaf := t.leafAt(id)
	base := unsafe.Pointer(&leaf.keys[0])
	var off uintptr
	if *(*int64)(unsafe.Add(base, 15*8)) < key {
		off = 16 * 8
	}
	if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
		off = next
	}
	if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
		off = next
	}
	if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
		off = next
	}
	if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
		off = next
	}
	pos := int(off >> 3)
	if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || pos < int(leaf.count)) {
		*(*int64)(unsafe.Add(unsafe.Pointer(&leaf.vals[0]), off)) = value
		return false
	}

	c := int(leaf.count)
	if c < maxKeys {
		if pos < c {
			copy(leaf.keys[pos+1:c+1], leaf.keys[pos:c])
			copy(leaf.vals[pos+1:c+1], leaf.vals[pos:c])
		}
		leaf.keys[pos] = key
		leaf.vals[pos] = value
		leaf.count = uint8(c + 1)
		t.length++
		return true
	}

	// Leaf is full (31 keys).
	// Optimization for sequential appends: if appending past the end and the left
	// sibling has free space, bulk-rotate entries left instead of splitting.
	if pos == maxKeys && depth > 0 {
		frame := stack[depth-1]
		if frame.idx > 0 {
			parent := &t.internals[frame.id]
			leftSib := t.leafAt(parent.children[frame.idx-1])
			lc := int(leftSib.count)
			if lc < maxKeys {
				move := maxKeys - lc // 1 <= move <= 16
				sepIdx := int(frame.idx) - 1
				leftSib.keys[lc] = parent.keys[sepIdx]
				leftSib.vals[lc] = parent.vals[sepIdx]
				if move > 1 {
					copy(leftSib.keys[lc+1:maxKeys], leaf.keys[0:move-1])
					copy(leftSib.vals[lc+1:maxKeys], leaf.vals[0:move-1])
				}
				leftSib.count = maxKeys

				parent.keys[sepIdx] = leaf.keys[move-1]
				parent.vals[sepIdx] = leaf.vals[move-1]

				rem := maxKeys - move // 15 <= rem <= 30
				copy(leaf.keys[0:rem], leaf.keys[move:maxKeys])
				copy(leaf.vals[0:rem], leaf.vals[move:maxKeys])
				leaf.keys[rem] = key
				leaf.vals[rem] = value
				newRC := rem + 1
				leaf.count = uint8(newRC)
				if newRC < maxKeys {
					copy(leaf.keys[newRC:], sentinelKeys[newRC:])
				}
				t.length++
				return true
			}
		}
	}

	// Split full leaf (31 existing + 1 new = 32 -> left=16, med=1, right=15).
	rightID := t.allocLeaf()
	right := t.leafAt(rightID)
	var medKey, medVal int64
	if pos < 16 {
		medKey = leaf.keys[15]
		medVal = leaf.vals[15]
		copy(right.keys[0:15], leaf.keys[16:31])
		copy(right.vals[0:15], leaf.vals[16:31])
		copy(right.keys[15:], sentinelKeys[15:])
		right.count = 15

		copy(leaf.keys[pos+1:16], leaf.keys[pos:15])
		copy(leaf.vals[pos+1:16], leaf.vals[pos:15])
		leaf.keys[pos] = key
		leaf.vals[pos] = value
		copy(leaf.keys[16:], sentinelKeys[16:])
		leaf.count = 16
	} else if pos == 16 {
		medKey = key
		medVal = value
		copy(right.keys[0:15], leaf.keys[16:31])
		copy(right.vals[0:15], leaf.vals[16:31])
		copy(right.keys[15:], sentinelKeys[15:])
		right.count = 15

		copy(leaf.keys[16:], sentinelKeys[16:])
		leaf.count = 16
	} else {
		medKey = leaf.keys[16]
		medVal = leaf.vals[16]
		rPos := pos - 17
		if rPos > 0 {
			copy(right.keys[0:rPos], leaf.keys[17:pos])
			copy(right.vals[0:rPos], leaf.vals[17:pos])
		}
		right.keys[rPos] = key
		right.vals[rPos] = value
		if pos < maxKeys {
			copy(right.keys[rPos+1:15], leaf.keys[pos:31])
			copy(right.vals[rPos+1:15], leaf.vals[pos:31])
		}
		copy(right.keys[15:], sentinelKeys[15:])
		right.count = 15

		copy(leaf.keys[16:], sentinelKeys[16:])
		leaf.count = 16
	}

	t.length++

	// Propagate promoted entry up the stack.
	for depth > 0 {
		depth--
		pID := stack[depth].id
		pPos := int(stack[depth].idx)
		p := &t.internals[pID]
		pc := int(p.count)
		if pc < maxKeys {
			if pPos < pc {
				copy(p.keys[pPos+1:pc+1], p.keys[pPos:pc])
				copy(p.vals[pPos+1:pc+1], p.vals[pPos:pc])
				copy(p.children[pPos+2:pc+2], p.children[pPos+1:pc+1])
			}
			p.keys[pPos] = medKey
			p.vals[pPos] = medVal
			p.children[pPos+1] = rightID
			p.count = uint8(pc + 1)
			return true
		}

		// Parent internal node is full (31 keys). Allocate right sibling first
		// before taking pointers into t.internals.
		newRightID := t.allocInternal()
		p = &t.internals[pID]
		r := &t.internals[newRightID]
		var upKey, upVal int64
		if pPos < 16 {
			upKey = p.keys[15]
			upVal = p.vals[15]
			copy(r.keys[0:15], p.keys[16:31])
			copy(r.vals[0:15], p.vals[16:31])
			copy(r.children[0:16], p.children[16:32])
			copy(r.keys[15:], sentinelKeys[15:])
			r.count = 15

			copy(p.keys[pPos+1:16], p.keys[pPos:15])
			copy(p.vals[pPos+1:16], p.vals[pPos:15])
			copy(p.children[pPos+2:17], p.children[pPos+1:16])
			p.keys[pPos] = medKey
			p.vals[pPos] = medVal
			p.children[pPos+1] = rightID
			copy(p.keys[16:], sentinelKeys[16:])
			p.count = 16
		} else if pPos == 16 {
			upKey = medKey
			upVal = medVal
			copy(r.keys[0:15], p.keys[16:31])
			copy(r.vals[0:15], p.vals[16:31])
			r.children[0] = rightID
			copy(r.children[1:16], p.children[17:32])
			copy(r.keys[15:], sentinelKeys[15:])
			r.count = 15

			copy(p.keys[16:], sentinelKeys[16:])
			p.count = 16
		} else {
			upKey = p.keys[16]
			upVal = p.vals[16]
			rPos := pPos - 17
			if rPos > 0 {
				copy(r.keys[0:rPos], p.keys[17:pPos])
				copy(r.vals[0:rPos], p.vals[17:pPos])
			}
			r.keys[rPos] = medKey
			r.vals[rPos] = medVal
			if pPos < maxKeys {
				copy(r.keys[rPos+1:15], p.keys[pPos:31])
				copy(r.vals[rPos+1:15], p.vals[pPos:31])
			}
			copy(r.children[0:rPos+1], p.children[17:pPos+1])
			r.children[rPos+1] = rightID
			if pPos < maxKeys {
				copy(r.children[rPos+2:16], p.children[pPos+1:32])
			}
			copy(r.keys[15:], sentinelKeys[15:])
			r.count = 15

			copy(p.keys[16:], sentinelKeys[16:])
			p.count = 16
		}

		medKey = upKey
		medVal = upVal
		rightID = newRightID
	}

	// Root split: create a new root.
	newRootID := t.allocInternal()
	nr := &t.internals[newRootID]
	nr.keys = sentinelKeys
	nr.keys[0] = medKey
	nr.vals[0] = medVal
	nr.children[0] = t.root
	nr.children[1] = rightID
	nr.count = 1
	t.root = newRootID
	t.height++
	return true
}

// Remove deletes key from the tree and returns true if it was present.
func (t *BTree) Remove(key int64) bool {
	h := t.height
	if h == 0 {
		return false
	}

	var stack [16]pathEntry
	depth := 0
	id := t.root
	foundInternal := false
	var targetNodeID uint32
	var targetIdx int

	if h > 1 {
		internalsBase := unsafe.Pointer(unsafe.SliceData(t.internals))
		for lvl := h; lvl > 1; lvl-- {
			n := (*internalNode)(unsafe.Add(internalsBase, uintptr(id)*640))
			base := unsafe.Pointer(&n.keys[0])
			var off uintptr
			if *(*int64)(unsafe.Add(base, 15*8)) < key {
				off = 16 * 8
			}
			if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
				off = next
			}
			if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
				off = next
			}
			if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
				off = next
			}
			if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
				off = next
			}
			i := int(off >> 3)
			if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || i < int(n.count)) {
				foundInternal = true
				targetNodeID = id
				targetIdx = i
				stack[depth] = pathEntry{id: id, idx: uint8(i)}
				depth++
				id = *(*uint32)(unsafe.Add(unsafe.Pointer(&n.children[0]), off>>1))
				for lvl--; lvl > 1; lvl-- {
					cur := (*internalNode)(unsafe.Add(internalsBase, uintptr(id)*640))
					last := cur.count
					stack[depth] = pathEntry{id: id, idx: last}
					depth++
					id = cur.children[last]
				}
				break
			}
			stack[depth] = pathEntry{id: id, idx: uint8(i)}
			depth++
			id = *(*uint32)(unsafe.Add(unsafe.Pointer(&n.children[0]), off>>1))
		}
	}

	leaf := t.leafAt(id)
	delPos := -1
	if foundInternal {
		last := int(leaf.count) - 1
		tn := &t.internals[targetNodeID]
		tn.keys[targetIdx] = leaf.keys[last]
		tn.vals[targetIdx] = leaf.vals[last]
		leaf.keys[last] = math.MaxInt64
		leaf.count = uint8(last)
	} else {
		base := unsafe.Pointer(&leaf.keys[0])
		var off uintptr
		if *(*int64)(unsafe.Add(base, 15*8)) < key {
			off = 16 * 8
		}
		if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < key {
			off = next
		}
		if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < key {
			off = next
		}
		if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < key {
			off = next
		}
		if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < key {
			off = next
		}
		pos := int(off >> 3)
		if !(off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == key && (key != math.MaxInt64 || pos < int(leaf.count))) {
			return false
		}
		delPos = pos
		c := int(leaf.count)
		if pos+1 < c {
			copy(leaf.keys[pos:c-1], leaf.keys[pos+1:c])
			copy(leaf.vals[pos:c-1], leaf.vals[pos+1:c])
		}
		leaf.keys[c-1] = math.MaxInt64
		leaf.count = uint8(c - 1)
	}

	t.length--

	if depth == 0 {
		if leaf.count == 0 {
			t.freeLeaf(id)
			t.root = 0
			t.height = 0
		}
		return true
	}

	if leaf.count >= minKeys {
		return true
	}

	// Leaf underflow (leaf.count == 14). Check one sibling (left if available, else right).
	depth--
	pID := stack[depth].id
	cIdx := int(stack[depth].idx)
	p := &t.internals[pID]

	if cIdx > 0 {
		sep := cIdx - 1
		left := t.leafAt(p.children[sep])
		lc := int(left.count)
		if lc > minKeys {
			move := (lc - 14 + 1) / 2
			copy(leaf.keys[move:move+14], leaf.keys[0:14])
			copy(leaf.vals[move:move+14], leaf.vals[0:14])
			leaf.keys[move-1] = p.keys[sep]
			leaf.vals[move-1] = p.vals[sep]
			if move > 1 {
				copy(leaf.keys[0:move-1], left.keys[lc-move+1:lc])
				copy(leaf.vals[0:move-1], left.vals[lc-move+1:lc])
			}
			p.keys[sep] = left.keys[lc-move]
			p.vals[sep] = left.vals[lc-move]
			newLC := lc - move
			copy(left.keys[newLC:lc], sentinelKeys[:move])
			left.count = uint8(newLC)
			leaf.count = uint8(14 + move)
			return true
		}
		// Merge left (15) + p[sep] (1) + leaf (14) = 30 into left.
		left.keys[15] = p.keys[sep]
		left.vals[15] = p.vals[sep]
		copy(left.keys[16:30], leaf.keys[0:14])
		copy(left.vals[16:30], leaf.vals[0:14])
		left.count = 30
		t.freeLeaf(id)

		pc := int(p.count)
		if sep+1 < pc {
			copy(p.keys[sep:pc-1], p.keys[sep+1:pc])
			copy(p.vals[sep:pc-1], p.vals[sep+1:pc])
			copy(p.children[cIdx:pc], p.children[cIdx+1:pc+1])
		}
		p.keys[pc-1] = math.MaxInt64
		p.count = uint8(pc - 1)
	} else {
		rightID := p.children[1]
		right := t.leafAt(rightID)
		rc := int(right.count)
		if rc > minKeys {
			var move int
			if delPos == 0 {
				// Sequential front-delete fast path: drain right sibling down to minKeys
				// in one bulk copy so the next underflow merges immediately.
				move = rc - minKeys
			} else {
				move = (rc - 14 + 1) / 2
			}
			leaf.keys[14] = p.keys[0]
			leaf.vals[14] = p.vals[0]
			if move > 1 {
				copy(leaf.keys[15:14+move], right.keys[0:move-1])
				copy(leaf.vals[15:14+move], right.vals[0:move-1])
			}
			p.keys[0] = right.keys[move-1]
			p.vals[0] = right.vals[move-1]
			newRC := rc - move
			copy(right.keys[0:newRC], right.keys[move:rc])
			copy(right.vals[0:newRC], right.vals[move:rc])
			copy(right.keys[newRC:rc], sentinelKeys[:move])
			right.count = uint8(newRC)
			leaf.count = uint8(14 + move)
			return true
		}
		// Merge leaf (14) + p[0] (1) + right (15) = 30 into leaf.
		leaf.keys[14] = p.keys[0]
		leaf.vals[14] = p.vals[0]
		copy(leaf.keys[15:30], right.keys[0:15])
		copy(leaf.vals[15:30], right.vals[0:15])
		leaf.count = 30
		t.freeLeaf(rightID)

		pc := int(p.count)
		if pc > 1 {
			copy(p.keys[0:pc-1], p.keys[1:pc])
			copy(p.vals[0:pc-1], p.vals[1:pc])
			copy(p.children[1:pc], p.children[2:pc+1])
		}
		p.keys[pc-1] = math.MaxInt64
		p.count = uint8(pc - 1)
	}

	// Fix internal node underflows walking up the stack.
	curID := pID
	for {
		cur := &t.internals[curID]
		if depth == 0 {
			if cur.count == 0 {
				t.root = cur.children[0]
				t.height--
				t.freeInternal(curID)
			}
			return true
		}
		if cur.count >= minKeys {
			return true
		}

		depth--
		pID = stack[depth].id
		cIdx = int(stack[depth].idx)
		p = &t.internals[pID]

		if cIdx > 0 {
			sep := cIdx - 1
			left := &t.internals[p.children[sep]]
			lc := int(left.count)
			if lc > minKeys {
				move := (lc - 14 + 1) / 2
				copy(cur.keys[move:move+14], cur.keys[0:14])
				copy(cur.vals[move:move+14], cur.vals[0:14])
				copy(cur.children[move:move+15], cur.children[0:15])
				cur.keys[move-1] = p.keys[sep]
				cur.vals[move-1] = p.vals[sep]
				if move > 1 {
					copy(cur.keys[0:move-1], left.keys[lc-move+1:lc])
					copy(cur.vals[0:move-1], left.vals[lc-move+1:lc])
				}
				copy(cur.children[0:move], left.children[lc-move+1:lc+1])
				p.keys[sep] = left.keys[lc-move]
				p.vals[sep] = left.vals[lc-move]
				newLC := lc - move
				copy(left.keys[newLC:lc], sentinelKeys[:move])
				left.count = uint8(newLC)
				cur.count = uint8(14 + move)
				return true
			}
			// Merge left (15) + p[sep] (1) + cur (14) = 30 into left.
			left.keys[15] = p.keys[sep]
			left.vals[15] = p.vals[sep]
			copy(left.keys[16:30], cur.keys[0:14])
			copy(left.vals[16:30], cur.vals[0:14])
			copy(left.children[16:31], cur.children[0:15])
			left.count = 30
			t.freeInternal(curID)

			pc := int(p.count)
			if sep+1 < pc {
				copy(p.keys[sep:pc-1], p.keys[sep+1:pc])
				copy(p.vals[sep:pc-1], p.vals[sep+1:pc])
				copy(p.children[cIdx:pc], p.children[cIdx+1:pc+1])
			}
			p.keys[pc-1] = math.MaxInt64
			p.count = uint8(pc - 1)
		} else {
			rightID := p.children[1]
			right := &t.internals[rightID]
			rc := int(right.count)
			if rc > minKeys {
				move := (rc - 14 + 1) / 2
				cur.keys[14] = p.keys[0]
				cur.vals[14] = p.vals[0]
				if move > 1 {
					copy(cur.keys[15:14+move], right.keys[0:move-1])
					copy(cur.vals[15:14+move], right.vals[0:move-1])
				}
				copy(cur.children[15:15+move], right.children[0:move])
				p.keys[0] = right.keys[move-1]
				p.vals[0] = right.vals[move-1]
				newRC := rc - move
				copy(right.keys[0:newRC], right.keys[move:rc])
				copy(right.vals[0:newRC], right.vals[move:rc])
				copy(right.children[0:newRC+1], right.children[move:rc+1])
				copy(right.keys[newRC:rc], sentinelKeys[:move])
				right.count = uint8(newRC)
				cur.count = uint8(14 + move)
				return true
			}
			// Merge cur (14) + p[0] (1) + right (15) = 30 into cur.
			cur.keys[14] = p.keys[0]
			cur.vals[14] = p.vals[0]
			copy(cur.keys[15:30], right.keys[0:15])
			copy(cur.vals[15:30], right.vals[0:15])
			copy(cur.children[15:31], right.children[0:16])
			cur.count = 30
			t.freeInternal(rightID)

			pc := int(p.count)
			if pc > 1 {
				copy(p.keys[0:pc-1], p.keys[1:pc])
				copy(p.vals[0:pc-1], p.vals[1:pc])
				copy(p.children[1:pc], p.children[2:pc+1])
			}
			p.keys[pc-1] = math.MaxInt64
			p.count = uint8(pc - 1)
		}
		curID = pID
	}
}

// scanLeafTail handles the final leaf of a range query (where either hi or limit is reached).
func scanLeafTail(leaf *leafNode, start int, hi int64, out, limit int, outKeys, outVals []int64) int {
	c := int(leaf.count)
	avail := c - start
	rem := limit - out
	if avail > rem && leaf.keys[start+rem-1] <= hi {
		copy(outKeys[out:limit], leaf.keys[start:start+rem])
		copy(outVals[out:limit], leaf.vals[start:start+rem])
		return limit
	}
	end := c
	if avail > rem {
		end = start + rem
	}
	i := start
	for i < end && leaf.keys[i] <= hi {
		i++
	}
	if n := i - start; n > 0 {
		copy(outKeys[out:out+n], leaf.keys[start:i])
		copy(outVals[out:out+n], leaf.vals[start:i])
		out += n
	}
	return out
}

// Range writes ascending entries with lo <= key <= hi into outKeys/outVals
// up to len(outKeys) entries and returns the count written.
func (t *BTree) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	h := t.height
	if limit == 0 || lo > hi || h == 0 {
		return 0
	}
	// Bounds-check elimination hint for outVals.
	_ = outVals[limit-1]

	leafChunksBase := unsafe.Pointer(unsafe.SliceData(t.leafChunks))
	if h == 1 {
		chunk := *(**leafChunk)(unsafe.Add(leafChunksBase, uintptr(t.root>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
		leaf := &chunk[t.root&leafChunkMask]
		base := unsafe.Pointer(&leaf.keys[0])
		var off uintptr
		if *(*int64)(unsafe.Add(base, 15*8)) < lo {
			off = 16 * 8
		}
		if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < lo {
			off = next
		}
		if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < lo {
			off = next
		}
		if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < lo {
			off = next
		}
		if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < lo {
			off = next
		}
		start := int(off >> 3)
		c := int(leaf.count)
		if start >= c {
			return 0
		}
		if avail := c - start; avail <= limit && leaf.keys[c-1] <= hi {
			copy(outKeys[0:avail], leaf.keys[start:c])
			copy(outVals[0:avail], leaf.vals[start:c])
			return avail
		}
		return scanLeafTail(leaf, start, hi, 0, limit, outKeys, outVals)
	}

	internalsBase := unsafe.Pointer(unsafe.SliceData(t.internals))
	var stack [16]pathEntry
	sp := 0
	id := t.root
	hitInternal := false

	for lvl := h; lvl > 1; lvl-- {
		n := (*internalNode)(unsafe.Add(internalsBase, uintptr(id)*640))
		base := unsafe.Pointer(&n.keys[0])
		var off uintptr
		if *(*int64)(unsafe.Add(base, 15*8)) < lo {
			off = 16 * 8
		}
		if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < lo {
			off = next
		}
		if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < lo {
			off = next
		}
		if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < lo {
			off = next
		}
		if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < lo {
			off = next
		}
		i := int(off >> 3)
		stack[sp] = pathEntry{id: id, idx: uint8(i)}
		sp++
		if off < maxKeys*8 && *(*int64)(unsafe.Add(base, off)) == lo && (lo != math.MaxInt64 || i < int(n.count)) {
			hitInternal = true
			break
		}
		id = *(*uint32)(unsafe.Add(unsafe.Pointer(&n.children[0]), off>>1))
	}

	out := 0
	if !hitInternal {
		chunk := *(**leafChunk)(unsafe.Add(leafChunksBase, uintptr(id>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
		leaf := &chunk[id&leafChunkMask]
		base := unsafe.Pointer(&leaf.keys[0])
		var off uintptr
		if *(*int64)(unsafe.Add(base, 15*8)) < lo {
			off = 16 * 8
		}
		if next := off + 8*8; *(*int64)(unsafe.Add(base, off+7*8)) < lo {
			off = next
		}
		if next := off + 4*8; *(*int64)(unsafe.Add(base, off+3*8)) < lo {
			off = next
		}
		if next := off + 2*8; *(*int64)(unsafe.Add(base, off+1*8)) < lo {
			off = next
		}
		if next := off + 1*8; *(*int64)(unsafe.Add(base, off)) < lo {
			off = next
		}
		start := int(off >> 3)
		c := int(leaf.count)
		if start < c {
			avail := c - start
			if avail <= limit && leaf.keys[c-1] <= hi {
				copy(outKeys[0:avail], leaf.keys[start:c])
				copy(outVals[0:avail], leaf.vals[start:c])
				out = avail
				if out == limit {
					return out
				}
			} else {
				return scanLeafTail(leaf, start, hi, 0, limit, outKeys, outVals)
			}
		}
	}

	leafParentSP := h - 1
	for sp > 0 {
		f := &stack[sp-1]
		n := (*internalNode)(unsafe.Add(internalsBase, uintptr(f.id)*640))
		idx := int(f.idx)
		c := int(n.count)
		if idx >= c {
			sp--
			continue
		}

		if sp == leafParentSP {
			for idx < c {
				k := n.keys[idx]
				if k > hi {
					return out
				}
				outKeys[out] = k
				outVals[out] = n.vals[idx]
				out++
				if out == limit {
					return out
				}
				idx++
				leafID := n.children[idx]
				chunk := *(**leafChunk)(unsafe.Add(leafChunksBase, uintptr(leafID>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
				leaf := &chunk[leafID&leafChunkMask]
				lc := int(leaf.count)
				if lc <= limit-out && leaf.keys[lc-1] <= hi {
					copy(outKeys[out:out+lc], leaf.keys[:lc])
					copy(outVals[out:out+lc], leaf.vals[:lc])
					out += lc
					if out == limit {
						return out
					}
				} else {
					return scanLeafTail(leaf, 0, hi, out, limit, outKeys, outVals)
				}
			}
			sp--
			continue
		}

		k := n.keys[idx]
		if k > hi {
			return out
		}
		outKeys[out] = k
		outVals[out] = n.vals[idx]
		out++
		if out == limit {
			return out
		}
		f.idx = uint8(idx + 1)

		childID := n.children[idx+1]
		for sp < leafParentSP {
			stack[sp] = pathEntry{id: childID, idx: 0}
			sp++
			cn := (*internalNode)(unsafe.Add(internalsBase, uintptr(childID)*640))
			childID = cn.children[0]
		}
		chunk := *(**leafChunk)(unsafe.Add(leafChunksBase, uintptr(childID>>leafChunkShift)*unsafe.Sizeof((*leafChunk)(nil))))
		leaf := &chunk[childID&leafChunkMask]
		lc := int(leaf.count)
		if lc <= limit-out && leaf.keys[lc-1] <= hi {
			copy(outKeys[out:out+lc], leaf.keys[:lc])
			copy(outVals[out:out+lc], leaf.vals[:lc])
			out += lc
			if out == limit {
				return out
			}
		} else {
			return scanLeafTail(leaf, 0, hi, out, limit, outKeys, outVals)
		}
	}
	return out
}
