// Package btree implements a classic (CLRS-style) B-tree with minimum degree
// t = 16: entries live in every node, at most 31 keys per node, at least 15
// keys in every non-root node.
package btree

import (
	"math"
	"unsafe"
)

const (
	maxKeys  = 31 // 2t - 1
	minKeys  = 15 // t - 1
	maxDepth = 16 // far beyond any height reachable in memory with t = 16
	pad      = math.MaxInt64
)

// leaf is the layout shared by every node. keys has one extra slot; all
// slots at index >= n hold pad (MaxInt64) so that the in-node search can run
// a fixed, branch-free 5-step binary search over 32 slots. The struct is
// exactly 512 bytes: keys fill the first two 128-byte cache lines.
type leaf struct {
	keys [32]int64
	vals [maxKeys]int64
	n    int
}

// inner is an internal node: the common prefix plus child pointers. Children
// are typed *leaf; the tree height tells whether a child is really an inner.
type inner struct {
	leaf
	kids [maxKeys + 1]*leaf
}

var padKeys = func() (a [32]int64) {
	for i := range a {
		a[i] = pad
	}
	return
}()

func asInner(p *leaf) *inner { return (*inner)(unsafe.Pointer(p)) }

// lowerBound returns the number of keys < key (at most n, thanks to padding).
func lowerBound(k *[32]int64, key int64) int {
	i := 0
	if k[15] < key {
		i = 16
	}
	if k[(i+7)&31] < key {
		i += 8
	}
	if k[(i+3)&31] < key {
		i += 4
	}
	if k[(i+1)&31] < key {
		i += 2
	}
	if k[i&31] < key {
		i++
	}
	return i
}

// upperBound returns min(31, number of slots <= key); callers clip to n.
func upperBound(k *[32]int64, key int64) int {
	i := 0
	if k[15] <= key {
		i = 16
	}
	if k[(i+7)&31] <= key {
		i += 8
	}
	if k[(i+3)&31] <= key {
		i += 4
	}
	if k[(i+1)&31] <= key {
		i += 2
	}
	if k[i&31] <= key {
		i++
	}
	return i
}

// BTree is an ordered map from int64 to int64.
type BTree struct {
	root   *leaf
	height int
	count  int

	// Node pools: nodes are carved out of chunks (leaf chunks hold no
	// pointers, so the GC never scans them) and recycled through free lists.
	leafFree   []*leaf
	innerFree  []*inner
	leafChunk  []leaf
	innerChunk []inner
	leafTotal  int
	innerTotal int
}

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

func (t *BTree) newLeaf() *leaf {
	var p *leaf
	if n := len(t.leafFree); n > 0 {
		p = t.leafFree[n-1]
		t.leafFree = t.leafFree[:n-1]
	} else {
		if len(t.leafChunk) == 0 {
			sz := t.leafTotal
			if sz < 4 {
				sz = 4
			} else if sz > 1024 {
				sz = 1024
			}
			t.leafChunk = make([]leaf, sz)
			t.leafTotal += sz
		}
		p = &t.leafChunk[0]
		t.leafChunk = t.leafChunk[1:]
	}
	p.keys = padKeys
	p.n = 0
	return p
}

func (t *BTree) newInner() *inner {
	var p *inner
	if n := len(t.innerFree); n > 0 {
		p = t.innerFree[n-1]
		t.innerFree = t.innerFree[:n-1]
	} else {
		if len(t.innerChunk) == 0 {
			sz := t.innerTotal
			if sz < 2 {
				sz = 2
			} else if sz > 256 {
				sz = 256
			}
			t.innerChunk = make([]inner, sz)
			t.innerTotal += sz
		}
		p = &t.innerChunk[0]
		t.innerChunk = t.innerChunk[1:]
	}
	p.keys = padKeys
	p.n = 0
	return p
}

func (t *BTree) freeNode(p *leaf, isLeaf bool) {
	if isLeaf {
		t.leafFree = append(t.leafFree, p)
	} else {
		in := asInner(p)
		in.kids = [maxKeys + 1]*leaf{}
		t.innerFree = append(t.innerFree, in)
	}
}

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

// Height returns the number of levels.
func (t *BTree) Height() int { return t.height }

// Get returns the value stored for key.
func (t *BTree) Get(key int64) (int64, bool) {
	p := t.root
	if p == nil {
		return 0, false
	}
	for h := t.height; ; h-- {
		i := lowerBound(&p.keys, key)
		if p.keys[i&31] == key && i < p.n {
			return p.vals[i], true
		}
		if h <= 1 {
			return 0, false
		}
		p = asInner(p).kids[i&31]
	}
}

func insertLeafAt(p *leaf, i int, key, val int64) {
	n := p.n
	if i < n {
		copy(p.keys[i+1:n+1], p.keys[i:n])
		copy(p.vals[i+1:n+1], p.vals[i:n])
	}
	p.keys[i] = key
	p.vals[i] = val
	p.n = n + 1
}

func insertInnerAt(p *inner, i int, key, val int64, rc *leaf) {
	n := p.n
	if i < n {
		copy(p.keys[i+1:n+1], p.keys[i:n])
		copy(p.vals[i+1:n+1], p.vals[i:n])
		copy(p.kids[i+2:n+2], p.kids[i+1:n+1])
	}
	p.keys[i] = key
	p.vals[i] = val
	p.kids[i+1] = rc
	p.n = n + 1
}

// Insert adds or replaces an entry; it returns true if the key was new.
func (t *BTree) Insert(key, val int64) bool {
	p := t.root
	if p == nil {
		l := t.newLeaf()
		l.keys[0] = key
		l.vals[0] = val
		l.n = 1
		t.root = l
		t.height = 1
		t.count = 1
		return true
	}
	var pathN [maxDepth]*inner
	var pathI [maxDepth]int
	d := 0
	for h := t.height; h > 1; h-- {
		i := lowerBound(&p.keys, key)
		if p.keys[i&31] == key && i < p.n {
			p.vals[i] = val
			return false
		}
		in := asInner(p)
		pathN[d] = in
		pathI[d] = i
		d++
		p = in.kids[i&31]
	}
	i := lowerBound(&p.keys, key)
	if p.keys[i&31] == key && i < p.n {
		p.vals[i] = val
		return false
	}
	t.count++
	if p.n < maxKeys {
		insertLeafAt(p, i, key, val)
		return true
	}

	// Split the full leaf: 15 | median | 15, then insert into a half.
	right := t.newLeaf()
	medK, medV := p.keys[15], p.vals[15]
	copy(right.keys[:15], p.keys[16:31])
	copy(right.vals[:15], p.vals[16:31])
	right.n = 15
	copy(p.keys[15:31], padKeys[15:31])
	p.n = 15
	if i <= 15 {
		insertLeafAt(p, i, key, val)
	} else {
		insertLeafAt(right, i-16, key, val)
	}
	rc := right

	for d > 0 {
		d--
		par := pathN[d]
		pi := pathI[d]
		if par.n < maxKeys {
			insertInnerAt(par, pi, medK, medV, rc)
			return true
		}
		nr := t.newInner()
		nk, nv := par.keys[15], par.vals[15]
		copy(nr.keys[:15], par.keys[16:31])
		copy(nr.vals[:15], par.vals[16:31])
		copy(nr.kids[:16], par.kids[16:32])
		nr.n = 15
		copy(par.keys[15:31], padKeys[15:31])
		clear(par.kids[16:32])
		par.n = 15
		if pi <= 15 {
			insertInnerAt(par, pi, medK, medV, rc)
		} else {
			insertInnerAt(nr, pi-16, medK, medV, rc)
		}
		medK, medV, rc = nk, nv, &nr.leaf
	}

	nroot := t.newInner()
	nroot.keys[0] = medK
	nroot.vals[0] = medV
	nroot.kids[0] = t.root
	nroot.kids[1] = rc
	nroot.n = 1
	t.root = &nroot.leaf
	t.height++
	return true
}

// Remove deletes key; it returns true if the key was present.
func (t *BTree) Remove(key int64) bool {
	p := t.root
	if p == nil {
		return false
	}
	var pathN [maxDepth]*inner
	var pathI [maxDepth]int
	d := 0
	for h := t.height; h > 1; h-- {
		i := lowerBound(&p.keys, key)
		in := asInner(p)
		pathN[d] = in
		pathI[d] = i
		d++
		if p.keys[i&31] == key && i < p.n {
			// Found in an internal node: replace with the predecessor (the
			// last entry of the rightmost leaf of child i) and remove that.
			q := in.kids[i]
			for h--; h > 1; h-- {
				qi := asInner(q)
				pathN[d] = qi
				pathI[d] = q.n
				d++
				q = qi.kids[q.n]
			}
			last := q.n - 1
			p.keys[i] = q.keys[last]
			p.vals[i] = q.vals[last]
			q.keys[last] = pad
			q.n = last
			t.count--
			if last < minKeys {
				t.rebalance(q, &pathN, &pathI, d)
			}
			return true
		}
		p = in.kids[i&31]
	}
	i := lowerBound(&p.keys, key)
	if !(p.keys[i&31] == key && i < p.n) {
		return false
	}
	n := p.n - 1
	copy(p.keys[i:n], p.keys[i+1:n+1])
	copy(p.vals[i:n], p.vals[i+1:n+1])
	p.keys[n] = pad
	p.n = n
	t.count--
	if n < minKeys {
		t.rebalance(p, &pathN, &pathI, d)
	}
	return true
}

// rebalance repairs an underfull node cur (a leaf on entry) whose ancestors
// are pathN[0:d] with child indices pathI[0:d].
func (t *BTree) rebalance(cur *leaf, pathN *[maxDepth]*inner, pathI *[maxDepth]int, d int) {
	isLeaf := true
	for {
		if d == 0 { // cur is the root
			if cur.n == 0 {
				if isLeaf {
					t.root = nil
					t.height = 0
				} else {
					t.root = asInner(cur).kids[0]
					t.height--
				}
				t.freeNode(cur, isLeaf)
			}
			return
		}
		if cur.n >= minKeys {
			return
		}
		d--
		par := pathN[d]
		ci := pathI[d]
		if ci > 0 {
			l := par.kids[ci-1]
			if l.n > minKeys {
				rotateRight(par, ci, l, cur, isLeaf)
				return
			}
			if ci < par.n {
				r := par.kids[ci+1]
				if r.n > minKeys {
					rotateLeft(par, ci, cur, r, isLeaf)
					return
				}
			}
			merge(par, ci-1, l, cur, isLeaf)
			t.freeNode(cur, isLeaf)
		} else {
			r := par.kids[1]
			if r.n > minKeys {
				rotateLeft(par, 0, cur, r, isLeaf)
				return
			}
			merge(par, 0, cur, r, isLeaf)
			t.freeNode(r, isLeaf)
		}
		cur = &par.leaf
		isLeaf = false
	}
}

// rotateRight moves entries from left sibling l (child ci-1) through the
// parent into n (child ci), evening out their sizes.
func rotateRight(par *inner, ci int, l, n *leaf, isLeaf bool) {
	nl, nn := l.n, n.n
	m := (nl - nn) / 2
	copy(n.keys[m:m+nn], n.keys[:nn])
	copy(n.vals[m:m+nn], n.vals[:nn])
	n.keys[m-1] = par.keys[ci-1]
	n.vals[m-1] = par.vals[ci-1]
	copy(n.keys[:m-1], l.keys[nl-m+1:nl])
	copy(n.vals[:m-1], l.vals[nl-m+1:nl])
	par.keys[ci-1] = l.keys[nl-m]
	par.vals[ci-1] = l.vals[nl-m]
	if !isLeaf {
		ni, li := asInner(n), asInner(l)
		copy(ni.kids[m:m+nn+1], ni.kids[:nn+1])
		copy(ni.kids[:m], li.kids[nl-m+1:nl+1])
		clear(li.kids[nl-m+1 : nl+1])
	}
	copy(l.keys[nl-m:nl], padKeys[:m])
	l.n = nl - m
	n.n = nn + m
}

// rotateLeft moves entries from right sibling r (child ci+1) through the
// parent into n (child ci), evening out their sizes.
func rotateLeft(par *inner, ci int, n, r *leaf, isLeaf bool) {
	nn, nr := n.n, r.n
	m := (nr - nn) / 2
	n.keys[nn] = par.keys[ci]
	n.vals[nn] = par.vals[ci]
	copy(n.keys[nn+1:nn+m], r.keys[:m-1])
	copy(n.vals[nn+1:nn+m], r.vals[:m-1])
	par.keys[ci] = r.keys[m-1]
	par.vals[ci] = r.vals[m-1]
	copy(r.keys[:nr-m], r.keys[m:nr])
	copy(r.vals[:nr-m], r.vals[m:nr])
	if !isLeaf {
		ni, ri := asInner(n), asInner(r)
		copy(ni.kids[nn+1:nn+m+1], ri.kids[:m])
		copy(ri.kids[:nr-m+1], ri.kids[m:nr+1])
		clear(ri.kids[nr-m+1 : nr+1])
	}
	copy(r.keys[nr-m:nr], padKeys[:m])
	n.n = nn + m
	r.n = nr - m
}

// merge folds separator ci and child ci+1 (r) into child ci (l). The caller
// frees r.
func merge(par *inner, ci int, l, r *leaf, isLeaf bool) {
	nl, nr := l.n, r.n
	l.keys[nl] = par.keys[ci]
	l.vals[nl] = par.vals[ci]
	copy(l.keys[nl+1:nl+1+nr], r.keys[:nr])
	copy(l.vals[nl+1:nl+1+nr], r.vals[:nr])
	if !isLeaf {
		copy(asInner(l).kids[nl+1:nl+nr+2], asInner(r).kids[:nr+1])
	}
	l.n = nl + 1 + nr
	np := par.n
	copy(par.keys[ci:np-1], par.keys[ci+1:np])
	copy(par.vals[ci:np-1], par.vals[ci+1:np])
	copy(par.kids[ci+1:np], par.kids[ci+2:np+1])
	par.keys[np-1] = pad
	par.kids[np] = nil
	par.n = np - 1
}

// Range writes entries with lo <= key <= hi, in ascending order, into
// outKeys/outVals (at most len(outKeys) of them) and returns the count.
func (t *BTree) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	if lo > hi || limit == 0 || t.root == nil {
		return 0
	}
	outVals = outVals[:limit]
	var stN [maxDepth]*inner
	var stI [maxDepth]int
	sp := 0
	leafDepth := t.height - 1
	p := t.root
	for h := t.height; h > 1; h-- {
		i := lowerBound(&p.keys, lo)
		in := asInner(p)
		stN[sp] = in
		stI[sp] = i
		sp++
		p = in.kids[i&31]
	}
	i := lowerBound(&p.keys, lo)
	c := 0
	for {
		// Emit the run of leaf p starting at i.
		n := p.n
		j := upperBound(&p.keys, hi)
		if j > n {
			j = n
		}
		if i < j {
			cnt := j - i
			if rem := limit - c; cnt > rem {
				cnt = rem
			}
			copy(outKeys[c:c+cnt], p.keys[i:i+cnt])
			copy(outVals[c:c+cnt], p.vals[i:i+cnt])
			c += cnt
			if c == limit {
				return c
			}
		}
		if j < n {
			return c
		}
		// Climb to the next ancestor entry.
		for {
			if sp == 0 {
				return c
			}
			in := stN[sp-1]
			k := stI[sp-1]
			if k < in.n {
				key := in.keys[k]
				if key > hi {
					return c
				}
				outKeys[c] = key
				outVals[c] = in.vals[k]
				c++
				if c == limit {
					return c
				}
				stI[sp-1] = k + 1
				q := in.kids[k+1]
				for sp < leafDepth {
					qi := asInner(q)
					stN[sp] = qi
					stI[sp] = 0
					sp++
					q = qi.kids[0]
				}
				p = q
				i = 0
				break
			}
			sp--
		}
	}
}
