package skiplist

import (
	"math/bits"
	"unsafe"
)

const (
	// Classic randomized skip list with p = 1/2 and maxHeight = 32.
	// (1/p)^maxHeight = 2^32 >= 2^32.
	maxHeight = 32

	// Arena layout (addressed in 8-byte uint64 word units via uint32 refs):
	//   word 0..13 : unused (nilNode == 0)
	//   word 14..31: header node (key/val at bytes 112..127, next[0..31] at bytes 128..255,
	//                putting all 32 header forward links into a single 128-byte cache line)
	//   word 32..  : height-segregated node slabs (starting at byte 256, 128-byte aligned)
	nilNode      = uint32(0)
	headNode     = uint32(14)
	arenaStart   = uint32(32)
	initArenaCap = 64 // grows by 2x up to 4,194,304 words (32 MiB), then 1.5x

	// Byte offsets within every node:
	//   [0..7]   key   int64
	//   [8..15]  val   int64
	//   [16..]   next  [h]uint32
	offVal  = uintptr(8)
	offNext = uintptr(16)

	numClasses = 11

	// Fixed seed for reproducible xorshift64* PRNG.
	rngSeed = uint64(0x910A2DEC89025CC1)
)

// Height-to-size-class mapping: segregates nodes by height so tall nodes
// (levels >= 4) are packed densely into dedicated cache lines and fit in L2.
var heightToClass = [maxHeight + 1]uint8{
	0, // unused
	0, // h = 1  (24 B, 3 words)
	1, // h = 2  (24 B, 3 words)
	2, // h = 3  (32 B, 4 words)
	3, // h = 4  (32 B, 4 words)
	4, // h = 5  (40 B, 5 words)
	5, // h = 6  (40 B, 5 words)
	6, // h = 7  (48 B, 6 words)
	7, // h = 8  (48 B, 6 words)
	8, 8, 8, 8, // h = 9..12  (64 B, 8 words)
	9, 9, 9, 9, // h = 13..16 (80 B, 10 words)
	10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, // h = 17..32 (144 B, 18 words)
}

var classWords = [numClasses]uint32{
	3, 3, 4, 4, 5, 5, 6, 6, 8, 10, 18,
}

var classInitSlab = [numClasses]uint32{
	16, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32,
}

var classMaxSlab = [numClasses]uint32{
	2048, 2048, 2048, 2048, 1024, 1024, 512, 512, 512, 256, 256,
}

type sizeClass struct {
	freeHead uint32
	slabCur  uint32
	slabEnd  uint32
	nextSlab uint32
}

// SkipList is an ordered map from int64 keys to int64 values backed by a
// randomized skip list stored in a pointer-free, height-segregated arena.
type SkipList struct {
	arena    []uint64
	height   int
	length   int
	rng      uint64
	arenaLen uint32
	classes  [numClasses]sizeClass
}

// New creates an empty SkipList.
func New() *SkipList {
	t := &SkipList{
		arena:    make([]uint64, initArenaCap),
		rng:      rngSeed,
		arenaLen: arenaStart,
	}
	for c := 0; c < numClasses; c++ {
		t.classes[c].nextSlab = classInitSlab[c]
	}
	return t
}

// randomHeight draws a geometric(p = 1/2) height in [1, maxHeight] using a
// self-contained xorshift64* generator.
func (t *SkipList) randomHeight() int {
	x := t.rng
	x ^= x >> 12
	x ^= x << 25
	x ^= x >> 27
	t.rng = x
	h := bits.LeadingZeros64(x*0x2545F4914F6CDD1D) + 1
	if h > maxHeight {
		h = maxHeight
	}
	return h
}

func (t *SkipList) allocNode(h int) uint32 {
	c := heightToClass[h]
	sc := &t.classes[c]
	if ref := sc.freeHead; ref != nilNode {
		base := unsafe.Pointer(unsafe.SliceData(t.arena))
		sc.freeHead = *(*uint32)(unsafe.Add(base, uintptr(ref)<<3))
		return ref
	}
	w := classWords[c]
	cur := sc.slabCur
	if cur+w <= sc.slabEnd {
		sc.slabCur = cur + w
		return cur
	}
	return t.allocNodeSlow(c, w)
}

func (t *SkipList) allocNodeSlow(c uint8, w uint32) uint32 {
	sc := &t.classes[c]
	slab := sc.nextSlab
	if slab < classMaxSlab[c] {
		sc.nextSlab = slab << 1
	}
	need := uint64(t.arenaLen) + uint64(slab)
	if need > uint64(len(t.arena)) {
		newCap := uint64(len(t.arena))
		for newCap < need {
			if newCap < 4194304 {
				newCap <<= 1
			} else {
				newCap += newCap >> 1
			}
		}
		newArena := make([]uint64, newCap)
		copy(newArena, t.arena[:t.arenaLen])
		t.arena = newArena
	}
	cur := t.arenaLen
	sc.slabCur = cur + w
	sc.slabEnd = cur + slab
	t.arenaLen = cur + slab
	return cur
}

func (t *SkipList) freeNode(base unsafe.Pointer, ref uint32, h int) {
	c := heightToClass[h]
	sc := &t.classes[c]
	*(*uint32)(unsafe.Add(base, uintptr(ref)<<3)) = sc.freeHead
	sc.freeHead = ref
}

// Get returns the value stored for key and true, or (0, false) if absent.
func (t *SkipList) Get(key int64) (value int64, ok bool) {
	h := t.height
	if h == 0 {
		return 0, false
	}
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	curPtr := unsafe.Add(base, uintptr(headNode)<<3)
	var fence uint32
	for off := offNext + uintptr(h-1)<<2; off >= offNext; off -= 4 {
		for {
			next := *(*uint32)(unsafe.Add(curPtr, off))
			if next == fence {
				break
			}
			nextPtr := unsafe.Add(base, uintptr(next)<<3)
			nk := *(*int64)(nextPtr)
			if nk < key {
				curPtr = nextPtr
				continue
			}
			if nk == key {
				return *(*int64)(unsafe.Add(nextPtr, offVal)), true
			}
			fence = next
			break
		}
	}
	return 0, false
}

// Insert adds (key, value) if key is absent and returns true, or replaces its
// value if key is present and returns false.
func (t *SkipList) Insert(key, value int64) bool {
	var update [maxHeight]uint32
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	cur := headNode
	curPtr := unsafe.Add(base, uintptr(headNode)<<3)
	var fence uint32

	for l := t.height - 1; l >= 0; l-- {
		off := offNext + uintptr(l)<<2
		for {
			next := *(*uint32)(unsafe.Add(curPtr, off))
			if next == fence {
				break
			}
			nextPtr := unsafe.Add(base, uintptr(next)<<3)
			nk := *(*int64)(nextPtr)
			if nk < key {
				cur = next
				curPtr = nextPtr
				continue
			}
			if nk == key {
				*(*int64)(unsafe.Add(nextPtr, offVal)) = value
				return false
			}
			fence = next
			break
		}
		update[l] = cur
	}

	h := t.randomHeight()
	node := t.allocNode(h)
	// Reload base in case allocNode grew t.arena.
	base = unsafe.Pointer(unsafe.SliceData(t.arena))
	nodePtr := unsafe.Add(base, uintptr(node)<<3)
	*(*int64)(nodePtr) = key
	*(*int64)(unsafe.Add(nodePtr, offVal)) = value

	if h == 1 {
		if t.height == 0 {
			t.height = 1
		}
		predPtr := unsafe.Add(base, uintptr(cur)<<3)
		*(*uint32)(unsafe.Add(nodePtr, offNext)) = fence
		*(*uint32)(unsafe.Add(predPtr, offNext)) = node
	} else {
		if h > t.height {
			for l := t.height; l < h; l++ {
				update[l] = headNode
			}
			t.height = h
		}
		for l := 0; l < h; l++ {
			off := offNext + uintptr(l)<<2
			predPtr := unsafe.Add(base, uintptr(update[l])<<3)
			*(*uint32)(unsafe.Add(nodePtr, off)) = *(*uint32)(unsafe.Add(predPtr, off))
			*(*uint32)(unsafe.Add(predPtr, off)) = node
		}
	}

	t.length++
	return true
}

// Remove deletes key from the list and returns true if present, else false.
func (t *SkipList) Remove(key int64) bool {
	h := t.height
	if h == 0 {
		return false
	}
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	headPtr := unsafe.Add(base, uintptr(headNode)<<3)

	// Fast path for removing the minimum key (or keys smaller than the minimum).
	first := *(*uint32)(unsafe.Add(headPtr, offNext))
	firstPtr := unsafe.Add(base, uintptr(first)<<3)
	fk := *(*int64)(firstPtr)
	if key <= fk {
		if key < fk {
			return false
		}
		l := 0
		for l < h {
			off := offNext + uintptr(l)<<2
			if *(*uint32)(unsafe.Add(headPtr, off)) != first {
				break
			}
			*(*uint32)(unsafe.Add(headPtr, off)) = *(*uint32)(unsafe.Add(firstPtr, off))
			l++
		}
		if l == h {
			for h > 0 && *(*uint32)(unsafe.Add(headPtr, offNext+uintptr(h-1)<<2)) == nilNode {
				h--
			}
			t.height = h
		}
		t.freeNode(base, first, l)
		t.length--
		return true
	}

	curPtr := headPtr
	var fence uint32
	for l := h - 1; l >= 0; l-- {
		off := offNext + uintptr(l)<<2
		for {
			next := *(*uint32)(unsafe.Add(curPtr, off))
			if next == fence {
				break
			}
			nextPtr := unsafe.Add(base, uintptr(next)<<3)
			nk := *(*int64)(nextPtr)
			if nk < key {
				curPtr = nextPtr
				continue
			}
			if nk == key {
				target := next
				targetPtr := nextPtr
				targetHeight := l + 1
				*(*uint32)(unsafe.Add(curPtr, off)) = *(*uint32)(unsafe.Add(targetPtr, off))
				for ll := l - 1; ll >= 0; ll-- {
					loff := offNext + uintptr(ll)<<2
					for {
						nn := *(*uint32)(unsafe.Add(curPtr, loff))
						if nn == target {
							break
						}
						curPtr = unsafe.Add(base, uintptr(nn)<<3)
					}
					*(*uint32)(unsafe.Add(curPtr, loff)) = *(*uint32)(unsafe.Add(targetPtr, loff))
				}
				if targetHeight == h {
					for h > 0 && *(*uint32)(unsafe.Add(headPtr, offNext+uintptr(h-1)<<2)) == nilNode {
						h--
					}
					t.height = h
				}
				t.freeNode(base, target, targetHeight)
				t.length--
				return true
			}
			fence = next
			break
		}
	}
	return false
}

// 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 *SkipList) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	if len(outVals) < limit {
		limit = len(outVals)
	}
	h := t.height
	if lo > hi || limit == 0 || h == 0 {
		return 0
	}

	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	curPtr := unsafe.Add(base, uintptr(headNode)<<3)
	var fence uint32
	var node uint32

	for off := offNext + uintptr(h-1)<<2; off >= offNext; off -= 4 {
		for {
			next := *(*uint32)(unsafe.Add(curPtr, off))
			if next == fence {
				break
			}
			nextPtr := unsafe.Add(base, uintptr(next)<<3)
			nk := *(*int64)(nextPtr)
			if nk < lo {
				curPtr = nextPtr
				continue
			}
			if nk == lo {
				node = next
				goto scan
			}
			fence = next
			break
		}
	}
	node = fence

scan:
	outK := unsafe.Pointer(unsafe.SliceData(outKeys))
	outV := unsafe.Pointer(unsafe.SliceData(outVals))
	count := 0
	for node != nilNode && count < limit {
		p := unsafe.Add(base, uintptr(node)<<3)
		nk := *(*int64)(p)
		if nk > hi {
			break
		}
		next := *(*uint32)(unsafe.Add(p, offNext))
		nv := *(*int64)(unsafe.Add(p, offVal))
		*(*int64)(unsafe.Add(outK, uintptr(count)<<3)) = nk
		*(*int64)(unsafe.Add(outV, uintptr(count)<<3)) = nv
		count++
		node = next
	}
	return count
}

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

// Height returns the height of the tallest node currently in the list, or 0 if empty.
func (t *SkipList) Height() int {
	return t.height
}

// LevelCount returns the number of nodes whose tower reaches level.
func (t *SkipList) LevelCount(level int) int {
	if level < 0 || level >= t.height {
		return 0
	}
	base := unsafe.Pointer(unsafe.SliceData(t.arena))
	off := offNext + uintptr(level)<<2
	node := *(*uint32)(unsafe.Add(base, uintptr(headNode)<<3+off))
	count := 0
	for node != nilNode {
		count++
		node = *(*uint32)(unsafe.Add(base, uintptr(node)<<3+off))
	}
	return count
}
