// Package skiplist implements a classic randomized (Pugh) skip list mapping
// int64 keys to int64 values.
//
// Layout: all nodes live in one pointer-free arena ([]uint32, so the GC never
// scans it). A node at word offset `off` is
//
//	off+0..1  key   (int64)
//	off+2..3  value (int64)
//	off+4..   h forward links (uint32 word offsets), one per level 0..h-1
//
// Offset 0 is a tail sentinel whose key is MaxInt64; a link value of 0 means
// "null" and, because the sentinel's key is MaxInt64, search loops need no
// separate null check. The header lives at offset 4 with maxHeight links.
package skiplist

import (
	"math"
	"math/bits"
	"unsafe"
)

const (
	maxHeight = 16 // p = 1/4: 4^16 = 2^32
	tailOff   = 0
	headOff   = 4
	firstOff  = headOff + 4 + maxHeight
	initCap   = 1 << 12
)

type SkipList struct {
	arena []uint32
	level int // number of levels in use (height of the tallest node)
	count int
	rng   uint64
	free  [maxHeight + 1]uint32 // free lists per tower height, chained via link 0
}

func New() *SkipList {
	t := &SkipList{rng: 0x2545F4914F6CDD1D}
	t.arena = make([]uint32, firstOff, initCap)
	*(*int64)(unsafe.Pointer(&t.arena[tailOff])) = math.MaxInt64
	return t
}

func keyAt(base unsafe.Pointer, off uint32) int64 {
	return *(*int64)(unsafe.Add(base, uintptr(off)*4))
}

func valPtr(base unsafe.Pointer, off uint32) *int64 {
	return (*int64)(unsafe.Add(base, (uintptr(off)+2)*4))
}

func link(base unsafe.Pointer, off uint32, i int) *uint32 {
	return (*uint32)(unsafe.Add(base, (uintptr(off)+4+uintptr(i))*4))
}

func (t *SkipList) randomHeight() int {
	t.rng += 0x9E3779B97F4A7C15
	z := t.rng
	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
	z ^= z >> 31
	h := 1 + bits.TrailingZeros64(z)>>1
	if h > maxHeight {
		h = maxHeight
	}
	return h
}

func (t *SkipList) alloc(h int) uint32 {
	if f := t.free[h]; f != 0 {
		base := unsafe.Pointer(unsafe.SliceData(t.arena))
		t.free[h] = *link(base, f, 0)
		return f
	}
	off := len(t.arena)
	need := off + 4 + h
	if need > cap(t.arena) {
		if need > math.MaxUint32 {
			panic("skiplist: arena overflow")
		}
		nc := cap(t.arena) * 2
		if nc > math.MaxUint32+1 {
			nc = math.MaxUint32 + 1
		}
		na := make([]uint32, off, nc)
		copy(na, t.arena)
		t.arena = na
	}
	t.arena = t.arena[:need]
	return uint32(off)
}

func (t *SkipList) Insert(key, value int64) bool {
	var update [maxHeight]uint32
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	x := uint32(headOff)
	lvl := t.level
	for i := lvl - 1; i >= 0; i-- {
		nx := *link(base, x, i)
		nk := keyAt(base, nx)
		for nk < key {
			x = nx
			nx = *link(base, x, i)
			nk = keyAt(base, nx)
		}
		if nk == key && nx != tailOff {
			*valPtr(base, nx) = value
			return false
		}
		update[i] = x
	}
	h := t.randomHeight()
	for i := lvl; i < h; i++ {
		update[i] = headOff
	}
	if h > lvl {
		t.level = h
	}
	n := t.alloc(h)
	base = unsafe.Pointer(unsafe.SliceData(t.arena))
	*(*int64)(unsafe.Add(base, uintptr(n)*4)) = key
	*valPtr(base, n) = value
	for i := 0; i < h; i++ {
		p := link(base, update[i], i)
		*link(base, n, i) = *p
		*p = n
	}
	t.count++
	return true
}

func (t *SkipList) Get(key int64) (value int64, ok bool) {
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	x := uint32(headOff)
	for i := t.level - 1; i >= 0; i-- {
		nx := *link(base, x, i)
		nk := keyAt(base, nx)
		for nk < key {
			x = nx
			nx = *link(base, x, i)
			nk = keyAt(base, nx)
		}
		if nk == key && nx != tailOff {
			return *valPtr(base, nx), true
		}
	}
	return 0, false
}

func (t *SkipList) Remove(key int64) bool {
	var update [maxHeight]uint32
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	x := uint32(headOff)
	lvl := t.level
	for i := lvl - 1; i >= 0; i-- {
		nx := *link(base, x, i)
		for keyAt(base, nx) < key {
			x = nx
			nx = *link(base, x, i)
		}
		update[i] = x
	}
	if lvl == 0 {
		return false
	}
	target := *link(base, update[0], 0)
	if target == tailOff || keyAt(base, target) != key {
		return false
	}
	h := 0
	for h < lvl {
		p := link(base, update[h], h)
		if *p != target {
			break
		}
		*p = *link(base, target, h)
		h++
	}
	t.count--
	if t.count == 0 {
		// Empty: every header link is null again; reclaim the whole arena.
		t.arena = t.arena[:firstOff]
		t.free = [maxHeight + 1]uint32{}
		t.level = 0
		return true
	}
	*link(base, target, 0) = t.free[h]
	t.free[h] = target
	for t.level > 0 && *link(base, headOff, t.level-1) == tailOff {
		t.level--
	}
	return true
}

func (t *SkipList) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	if lo > hi || limit == 0 {
		return 0
	}
	outVals = outVals[:limit]
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	x := uint32(headOff)
	for i := t.level - 1; i >= 0; i-- {
		nx := *link(base, x, i)
		for keyAt(base, nx) < lo {
			x = nx
			nx = *link(base, x, i)
		}
	}
	nx := *link(base, x, 0)
	n := 0
	for nx != tailOff {
		k := keyAt(base, nx)
		if k > hi {
			break
		}
		outKeys[n] = k
		outVals[n] = *valPtr(base, nx)
		n++
		if n == limit {
			break
		}
		nx = *link(base, nx, 0)
	}
	return n
}

func (t *SkipList) Len() int { return t.count }

func (t *SkipList) Height() int { return t.level }

func (t *SkipList) LevelCount(level int) int {
	if level < 0 || level >= t.level {
		return 0
	}
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	c := 0
	for nx := *link(base, headOff, level); nx != tailOff; nx = *link(base, nx, level) {
		c++
	}
	return c
}
