package rbtree

import "unsafe"

const (
	idxMask uint32 = 0x7fffffff
	redMask uint32 = 0x80000000
)

// node is a compact 24-byte red-black tree node stored in a pointer-free arena.
// child[0] packs the left child index in bits 0..30 and the node color in bit 31
// (1 = red, 0 = black). child[1] stores the right child index (bit 31 is always 0).
// Index 0 is a permanent black nil sentinel at nodes[0].
type node struct {
	key   int64
	child [2]uint32
	val   int64
}

const nodeSize = unsafe.Sizeof(node{})

// RBTree is a classic red-black tree mapping int64 keys to int64 values.
type RBTree struct {
	nodes    []node
	root     uint32
	freeHead uint32
	size     int
	path     [64]uint32
}

// New creates an empty red-black tree.
func New() *RBTree {
	// Index 0 is the permanent black nil sentinel.
	return &RBTree{
		nodes: make([]node, 1, 32),
	}
}

func nodeAt(base unsafe.Pointer, idx uint32) *node {
	return (*node)(unsafe.Add(base, uintptr(idx)*nodeSize))
}

func isRed(base unsafe.Pointer, idx uint32) bool {
	return int32(nodeAt(base, idx).child[0]) < 0
}

func setRed(n *node) {
	n.child[0] |= redMask
}

func setBlack(n *node) {
	n.child[0] &^= redMask
}

func setChild(n *node, dir uint32, c uint32) {
	n.child[dir&1] = (n.child[dir&1] & redMask) | c
}

// rotate performs a left rotation if dir == 0, or a right rotation if dir == 1.
// Returns the new root index of the rotated subtree.
func rotate(base unsafe.Pointer, xIdx uint32, dir uint32) uint32 {
	d := dir & 1
	opp := d ^ 1
	x := nodeAt(base, xIdx)
	yIdx := x.child[opp] & idxMask
	y := nodeAt(base, yIdx)
	setChild(x, opp, y.child[d]&idxMask)
	setChild(y, d, xIdx)
	return yIdx
}

//go:noinline
func (t *RBTree) grow() {
	newCap := cap(t.nodes) * 2
	if newCap < 32 {
		newCap = 32
	}
	next := make([]node, len(t.nodes), newCap)
	copy(next, t.nodes)
	t.nodes = next
}

// Get returns the value stored for key and true, or (0, false) if absent.
func (t *RBTree) Get(key int64) (int64, bool) {
	cur := t.root
	if cur == 0 {
		return 0, false
	}
	base := unsafe.Pointer(unsafe.SliceData(t.nodes))
	for {
		n := (*node)(unsafe.Add(base, uintptr(cur)*nodeSize))
		k := n.key
		if key == k {
			return n.val, true
		}
		l := n.child[0] & idxMask
		r := n.child[1]
		next := r
		if key < k {
			next = l
		}
		cur = next
		if cur == 0 {
			return 0, false
		}
	}
}

// Insert adds (key, value) if key is absent and returns true;
// otherwise it replaces the existing value and returns false.
func (t *RBTree) Insert(key, value int64) bool {
	base := unsafe.Pointer(unsafe.SliceData(t.nodes))
	cur := t.root
	if cur == 0 {
		var idx uint32
		if t.freeHead != 0 {
			idx = t.freeHead
			t.freeHead = nodeAt(base, idx).child[0]
		} else {
			nLen := len(t.nodes)
			if nLen == cap(t.nodes) {
				t.grow()
				base = unsafe.Pointer(unsafe.SliceData(t.nodes))
			}
			idx = uint32(nLen)
			t.nodes = t.nodes[:nLen+1]
		}
		n := nodeAt(base, idx)
		n.key = key
		n.val = value
		n.child[0] = 0 // black root, left = 0
		n.child[1] = 0
		t.root = idx
		t.size = 1
		return true
	}

	depth := 0
	for cur != 0 {
		n := nodeAt(base, cur)
		k := n.key
		if key == k {
			n.val = value
			return false
		}
		l := n.child[0] & idxMask
		r := n.child[1]
		less := key < k
		next := r
		if less {
			next = l
		}
		dir := uint32(1)
		if less {
			dir = 0
		}
		t.path[depth&63] = (cur << 1) | dir
		depth++
		cur = next
	}

	var newIdx uint32
	if t.freeHead != 0 {
		newIdx = t.freeHead
		t.freeHead = nodeAt(base, newIdx).child[0]
	} else {
		nLen := len(t.nodes)
		if nLen == cap(t.nodes) {
			t.grow()
			base = unsafe.Pointer(unsafe.SliceData(t.nodes))
		}
		newIdx = uint32(nLen)
		t.nodes = t.nodes[:nLen+1]
	}

	newNode := nodeAt(base, newIdx)
	newNode.key = key
	newNode.val = value
	newNode.child[0] = redMask // red leaf, left = 0
	newNode.child[1] = 0
	t.size++

	pEntry := t.path[(depth-1)&63]
	pIdx := pEntry >> 1
	pDir := pEntry & 1
	pNode := nodeAt(base, pIdx)
	setChild(pNode, pDir, newIdx)

	if int32(pNode.child[0]) >= 0 {
		return true
	}
	t.insertFixup(base, depth)
	return true
}

func (t *RBTree) insertFixup(base unsafe.Pointer, depth int) {
	pEntry := t.path[(depth-1)&63]
	pIdx := pEntry >> 1
	pDir := pEntry & 1
	pNode := nodeAt(base, pIdx)

	for {
		gEntry := t.path[(depth-2)&63]
		gIdx := gEntry >> 1
		gDir := gEntry & 1
		gNode := nodeAt(base, gIdx)
		uIdx := gNode.child[gDir^1] & idxMask
		uNode := nodeAt(base, uIdx)

		if int32(uNode.child[0]) < 0 {
			// Case 1: uncle is red -> recolor and move up two levels.
			setBlack(pNode)
			setBlack(uNode)
			depth -= 2
			if depth == 0 {
				return
			}
			setRed(gNode)
			pEntry = t.path[(depth-1)&63]
			pIdx = pEntry >> 1
			pDir = pEntry & 1
			pNode = nodeAt(base, pIdx)
			if int32(pNode.child[0]) >= 0 {
				return
			}
			continue
		}

		// Case 2: inner child -> rotate parent to align as outer child.
		if pDir != gDir {
			pIdx = rotate(base, pIdx, gDir)
			setChild(gNode, gDir, pIdx)
			pNode = nodeAt(base, pIdx)
		}

		// Case 3: outer child -> recolor and rotate grandparent.
		setBlack(pNode)
		setRed(gNode)
		subRoot := rotate(base, gIdx, gDir^1)
		if depth == 2 {
			t.root = subRoot
		} else {
			ggEntry := t.path[(depth-3)&63]
			setChild(nodeAt(base, ggEntry>>1), ggEntry&1, subRoot)
		}
		return
	}
}

// Remove deletes key if present and returns true, otherwise returns false.
func (t *RBTree) Remove(key int64) bool {
	cur := t.root
	if cur == 0 {
		return false
	}
	base := unsafe.Pointer(unsafe.SliceData(t.nodes))
	depth := 0
	for cur != 0 {
		n := nodeAt(base, cur)
		k := n.key
		if key == k {
			break
		}
		l := n.child[0] & idxMask
		r := n.child[1]
		less := key < k
		next := r
		if less {
			next = l
		}
		dir := uint32(1)
		if less {
			dir = 0
		}
		t.path[depth&63] = (cur << 1) | dir
		depth++
		cur = next
	}
	if cur == 0 {
		return false
	}

	target := nodeAt(base, cur)
	l := target.child[0] & idxMask
	r := target.child[1]
	if l != 0 && r != 0 {
		// Replace with in-order successor (minimum of right subtree).
		t.path[depth&63] = (cur << 1) | 1
		depth++
		succ := r
		for {
			sn := nodeAt(base, succ)
			sl := sn.child[0] & idxMask
			if sl == 0 {
				target.key = sn.key
				target.val = sn.val
				cur = succ
				target = sn
				l = 0
				r = sn.child[1]
				break
			}
			t.path[depth&63] = succ << 1
			depth++
			succ = sl
		}
	}

	child := l
	if child == 0 {
		child = r
	}
	wasBlack := int32(target.child[0]) >= 0

	t.size--
	if t.size == 0 {
		t.root = 0
		t.freeHead = 0
		t.nodes = t.nodes[:1]
		return true
	}

	// Push removed node onto the intrusive free list.
	target.child[0] = t.freeHead
	t.freeHead = cur

	if depth == 0 {
		t.root = child
		setBlack(nodeAt(base, child))
		return true
	}

	pEntry := t.path[(depth-1)&63]
	setChild(nodeAt(base, pEntry>>1), pEntry&1, child)

	if !wasBlack {
		return true
	}
	if isRed(base, child) {
		setBlack(nodeAt(base, child))
		return true
	}

	t.removeFixup(base, depth)
	return true
}

func (t *RBTree) removeFixup(base unsafe.Pointer, depth int) {
	for depth > 0 {
		pEntry := t.path[(depth-1)&63]
		pIdx := pEntry >> 1
		dir := pEntry & 1
		opp := dir ^ 1
		pNode := nodeAt(base, pIdx)

		wIdx := pNode.child[opp] & idxMask
		wNode := nodeAt(base, wIdx)

		// Case 1: sibling is red -> rotate parent so new sibling is black.
		if int32(wNode.child[0]) < 0 {
			setBlack(wNode)
			setRed(pNode)
			newSub := rotate(base, pIdx, dir)
			if depth == 1 {
				t.root = newSub
			} else {
				gpEntry := t.path[(depth-2)&63]
				setChild(nodeAt(base, gpEntry>>1), gpEntry&1, newSub)
			}
			t.path[(depth-1)&63] = (newSub << 1) | dir
			t.path[depth&63] = (pIdx << 1) | dir
			depth++

			wIdx = pNode.child[opp] & idxMask
			wNode = nodeAt(base, wIdx)
		}

		wNear := wNode.child[dir] & idxMask
		wFar := wNode.child[opp] & idxMask

		// Case 2: sibling's children are both black.
		if !isRed(base, wNear) && !isRed(base, wFar) {
			setRed(wNode)
			if int32(pNode.child[0]) < 0 {
				setBlack(pNode)
				return
			}
			depth--
			continue
		}

		// Case 3: far child is black, near child is red -> rotate sibling.
		if !isRed(base, wFar) {
			setBlack(nodeAt(base, wNear))
			setRed(wNode)
			newW := rotate(base, wIdx, opp)
			setChild(pNode, opp, newW)
			wFar = wIdx
			wIdx = newW
			wNode = nodeAt(base, wIdx)
		}

		// Case 4: far child is red -> recolor and rotate parent.
		wNode.child[0] = (wNode.child[0] & idxMask) | (pNode.child[0] & redMask)
		setBlack(pNode)
		setBlack(nodeAt(base, wFar))
		newSub := rotate(base, pIdx, dir)
		if depth == 1 {
			t.root = newSub
		} else {
			gpEntry := t.path[(depth-2)&63]
			setChild(nodeAt(base, gpEntry>>1), gpEntry&1, newSub)
		}
		return
	}
}

// Range writes up to len(outKeys) entries with lo <= key <= hi in ascending key
// order into outKeys and outVals, returning the number of entries written.
func (t *RBTree) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	if len(outVals) < limit {
		limit = len(outVals)
	}
	if limit == 0 || lo > hi || t.root == 0 {
		return 0
	}

	base := unsafe.Pointer(unsafe.SliceData(t.nodes))
	outK := unsafe.Pointer(unsafe.SliceData(outKeys))
	outV := unsafe.Pointer(unsafe.SliceData(outVals))

	// Phase 1: branchless descent to the first node with key >= lo,
	// keeping only ancestors with lo <= key <= hi on the stack.
	sp := 0
	cur := t.root
	for cur != 0 {
		n := nodeAt(base, cur)
		k := n.key
		if lo == k {
			t.path[sp&63] = cur
			sp++
			break
		}
		l := n.child[0] & idxMask
		r := n.child[1]
		less := lo < k
		t.path[sp&63] = cur
		inc := 0
		if less {
			inc = 1
		}
		if k > hi {
			inc = 0
		}
		sp += inc
		next := r
		if less {
			next = l
		}
		cur = next
	}

	// Phase 2: iterative in-order traversal starting from the stack.
	count := 0
	for sp > 0 {
		sp--
		cur = t.path[sp&63]
		n := nodeAt(base, cur)
		k := n.key
		if k > hi {
			return count
		}
		*(*int64)(unsafe.Add(outK, uintptr(count)*8)) = k
		*(*int64)(unsafe.Add(outV, uintptr(count)*8)) = n.val
		count++
		if count == limit || k == hi {
			return count
		}

		// Walk the left spine of the right subtree.
		cur = n.child[1]
		for cur != 0 {
			n = nodeAt(base, cur)
			l := n.child[0] & idxMask
			if l == 0 {
				k = n.key
				if k > hi {
					return count
				}
				*(*int64)(unsafe.Add(outK, uintptr(count)*8)) = k
				*(*int64)(unsafe.Add(outV, uintptr(count)*8)) = n.val
				count++
				if count == limit || k == hi {
					return count
				}
				cur = n.child[1]
				continue
			}
			t.path[sp&63] = cur
			sp++
			cur = l
		}
	}
	return count
}

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

// Height returns the number of nodes on the longest path from the root to a leaf.
func (t *RBTree) Height() int {
	if t.root == 0 {
		return 0
	}
	return heightRec(unsafe.Pointer(unsafe.SliceData(t.nodes)), t.root)
}

func heightRec(base unsafe.Pointer, idx uint32) int {
	if idx == 0 {
		return 0
	}
	n := nodeAt(base, idx)
	lh := heightRec(base, n.child[0]&idxMask)
	rh := heightRec(base, n.child[1])
	if lh > rh {
		return lh + 1
	}
	return rh + 1
}
