// Package heap implements an array-based binary min-heap of (key, value)
// int64 entries.
//
// Layout: one contiguous array of 16-byte entries. Tree position i lives at
// array index i+1 (index 0 is padding), so the children of index j are 2j and
// 2j+1 and the parent is j>>1. The array base is 128-byte aligned, so a pair
// of siblings always shares a 32-byte block and the 8 descendants three
// levels below index j (8j..8j+7) fill exactly one 128-byte cache line.
package heap

import (
	"math/bits"
	"unsafe"
)

type entry struct {
	k, v int64
}

type Heap struct {
	a    []entry // a[1..n] holds the heap; len(a)-1 is the capacity
	n    int
	sink int64 // absorbs the touch-ahead loads so they are not eliminated
}

// subtreeLevels: subtrees with at most this many levels are heapified with
// a plain level-by-level Floyd pass (they fit in L1).
const subtreeLevels = 12

func at(p unsafe.Pointer, i int) *entry {
	return (*entry)(unsafe.Add(p, uintptr(i)<<4))
}

func b2i(b bool) int {
	if b {
		return 1
	}
	return 0
}

// alloc returns a slice of capacity+1 entries whose element 0 is 128-byte
// aligned.
func alloc(capacity int) []entry {
	raw := make([]entry, capacity+1+8)
	off := int((128-(uintptr(unsafe.Pointer(&raw[0]))&127))&127) >> 4
	return raw[off : off+capacity+1 : off+capacity+1]
}

func New() *Heap {
	return &Heap{}
}

func (h *Heap) grow() {
	c := len(h.a) - 1
	nc := 2 * c
	if nc < 32 {
		nc = 32
	}
	na := alloc(nc)
	if h.n > 0 {
		copy(na[1:h.n+1], h.a[1:h.n+1])
	}
	h.a = na
}

func Build(keys, values []int64) *Heap {
	m := len(keys)
	values = values[:m]
	h := &Heap{}
	c := m
	if c < 32 {
		c = 32
	}
	h.a = alloc(c)
	dst := h.a[1 : m+1]
	for i := range dst {
		dst[i] = entry{keys[i], values[i]}
	}
	h.n = m
	if m > 1 {
		H := bits.Len(uint(m)) - 1 // level of the last index
		h.buildRec(1, H)
	}
	return h
}

// buildRec heapifies the subtree rooted at r, which spans `levels` levels
// below r, in post-order so that large builds stay cache friendly.
func (h *Heap) buildRec(r, levels int) {
	if levels <= subtreeLevels {
		h.heapifySub(r, levels)
		return
	}
	if 2*r > h.n {
		return
	}
	h.buildRec(2*r, levels-1)
	h.buildRec(2*r+1, levels-1)
	p := unsafe.Pointer(&h.a[0])
	h.siftDown(r, r, *at(p, r), h.n)
}

// heapifySub runs Floyd's construction on the subtree rooted at r.
func (h *Heap) heapifySub(r, levels int) {
	n := h.n
	last := n >> 1 // last internal node
	p := unsafe.Pointer(&h.a[0])
	for d := levels - 1; d >= 0; d-- {
		lo := r << d
		if lo > last {
			continue
		}
		hi := lo + (1 << d) - 1
		if hi > last {
			hi = last
		}
		for i := hi; i >= lo; i-- {
			h.siftDown(i, i, *at(p, i), n)
		}
	}
}

// siftDown places x into the hole at index j of a heap of n entries, where
// the subtrees below j are heaps. It is bottom-up: the hole is first moved
// to a leaf along the path of smaller children, then x sifts up from there,
// never above index start.
func (h *Heap) siftDown(start, j int, x entry, n int) {
	p := unsafe.Pointer(&h.a[0])
	L := len(h.a)
	var s int64
	c := 2 * j
	for c < n {
		// Touch the descendants four levels below j (16j..16j+15) so
		// their cache lines are in flight before the path reaches them.
		if f := c << 3; f+8 < L {
			s += at(p, f).k + at(p, f+8).k
		}
		e0 := at(p, c)
		e1 := at(p, c+1)
		k0, k1 := e0.k, e1.k
		c += b2i(k1 < k0) | (b2i(k1 == k0) & b2i(e1.v < e0.v))
		*at(p, j) = *at(p, c)
		j = c
		c = 2 * j
	}
	if c == n {
		*at(p, j) = *at(p, c)
		j = c
	}
	for j > start {
		pj := j >> 1
		pe := at(p, pj)
		if !(x.k < pe.k || (x.k == pe.k && x.v < pe.v)) {
			break
		}
		*at(p, j) = *pe
		j = pj
	}
	*at(p, j) = x
	h.sink += s
}

func (h *Heap) Push(key, value int64) {
	n := h.n + 1
	if n >= len(h.a) {
		h.grow()
	}
	h.n = n
	p := unsafe.Pointer(&h.a[0])
	j := n
	for j > 1 {
		pj := j >> 1
		pe := at(p, pj)
		if !(key < pe.k || (key == pe.k && value < pe.v)) {
			break
		}
		*at(p, j) = *pe
		j = pj
	}
	*at(p, j) = entry{key, value}
}

func (h *Heap) Peek() (key, value int64, ok bool) {
	if h.n == 0 {
		return 0, 0, false
	}
	e := h.a[1]
	return e.k, e.v, true
}

func (h *Heap) Pop() (key, value int64, ok bool) {
	n := h.n
	if n == 0 {
		return 0, 0, false
	}
	p := unsafe.Pointer(&h.a[0])
	top := *at(p, 1)
	last := *at(p, n)
	n--
	h.n = n
	if n > 0 {
		h.siftDown(1, 1, last, n)
	}
	return top.k, top.v, true
}

func (h *Heap) Replace(key, value int64) (oldKey, oldValue int64, ok bool) {
	n := h.n
	if n == 0 {
		h.Push(key, value)
		return 0, 0, false
	}
	p := unsafe.Pointer(&h.a[0])
	top := *at(p, 1)
	h.siftDown(1, 1, entry{key, value}, n)
	return top.k, top.v, true
}

func (h *Heap) PushPop(key, value int64) (outKey, outValue int64) {
	n := h.n
	if n == 0 {
		return key, value
	}
	p := unsafe.Pointer(&h.a[0])
	t := *at(p, 1)
	if !(t.k < key || (t.k == key && t.v < value)) {
		return key, value
	}
	h.siftDown(1, 1, entry{key, value}, n)
	return t.k, t.v
}

func (h *Heap) Len() int {
	return h.n
}

func (h *Heap) Slot(i int) (key, value int64) {
	e := h.a[i+1]
	return e.k, e.v
}
