// Package rtree is a Guttman R-tree (quadratic split, M = 16, m = 6) over
// two-dimensional integer rectangles with integer ids.
package rtree

import "math"

const (
	maxE = 16 // M
	minE = 6  // m

	chunkShift = 9
	chunkSize  = 1 << chunkShift
	chunkMask  = chunkSize - 1

	stackSize = 512 // >= 15 * maxHeight + 1
	maxDepth  = 32
)

// node is one R-tree node, stored structure-of-arrays. In a leaf, ch holds
// the ids; in an internal node it holds the pool indexes of the children.
// The node is padded to 384 bytes (three 128-byte cache lines); chunks are
// page aligned, so a node never straddles more lines than needed.
type node struct {
	n     int32
	level int32 // 0 for leaves
	x0    [maxE]int32
	y0    [maxE]int32
	x1    [maxE]int32
	y1    [maxE]int32
	ch    [maxE]int32
	_     [14]int32
}

type hitem struct {
	d uint64
	n int32
}

// RTree is the tree. Nodes live in a pool of fixed-size chunks addressed by
// int32 index, so node pointers stay valid when the pool grows and the pool
// holds no Go pointers (it is never scanned by the GC).
type RTree struct {
	chunks []*[chunkSize]node
	nnodes int32
	free   []int32
	root   int32
	size   int

	path     [maxDepth]int32
	pos      [maxDepth]int32
	stack    [stackSize]int32
	setAside []int32
	heap     []hitem
	resD     []uint64
	resI     []int32
}

func New() *RTree {
	t := &RTree{}
	t.root = t.alloc(0)
	return t
}

func (t *RTree) nd(i int32) *node {
	return &t.chunks[i>>chunkShift][i&chunkMask]
}

func (t *RTree) alloc(level int32) int32 {
	var i int32
	if k := len(t.free); k > 0 {
		i = t.free[k-1]
		t.free = t.free[:k-1]
	} else {
		i = t.nnodes
		if int(i>>chunkShift) == len(t.chunks) {
			t.chunks = append(t.chunks, new([chunkSize]node))
		}
		t.nnodes++
	}
	p := t.nd(i)
	p.n = 0
	p.level = level
	return i
}

func (t *RTree) freeNode(i int32) {
	t.free = append(t.free, i)
}

func bbox(nd *node) (x0, y0, x1, y1 int32) {
	cnt := int(nd.n)
	x0, y0, x1, y1 = nd.x0[0], nd.y0[0], nd.x1[0], nd.y1[0]
	for i := 1; i < cnt; i++ {
		j := i & (maxE - 1)
		x0 = min(x0, nd.x0[j])
		y0 = min(y0, nd.y0[j])
		x1 = max(x1, nd.x1[j])
		y1 = max(y1, nd.y1[j])
	}
	return
}

func (t *RTree) Insert(x0, y0, x1, y1, id int32) {
	t.insertAt(x0, y0, x1, y1, id, 0)
	t.size++
}

// insertAt inserts the entry (rect, v) into a node at the given level.
func (t *RTree) insertAt(x0, y0, x1, y1, v, level int32) {
	cur := t.root
	d := 0
	X0, Y0, X1, Y1 := int64(x0), int64(y0), int64(x1), int64(y1)
	for {
		nd := t.nd(cur)
		if nd.level == level {
			break
		}
		cnt := int(nd.n)
		best := 0
		bestEnl, bestArea := int64(math.MaxInt64), int64(math.MaxInt64)
		for i := 0; i < cnt; i++ {
			j := i & (maxE - 1)
			cx0, cy0, cx1, cy1 := int64(nd.x0[j]), int64(nd.y0[j]), int64(nd.x1[j]), int64(nd.y1[j])
			area := (cx1 - cx0) * (cy1 - cy0)
			enl := (max(cx1, X1)-min(cx0, X0))*(max(cy1, Y1)-min(cy0, Y0)) - area
			if enl < bestEnl || (enl == bestEnl && area < bestArea) {
				best, bestEnl, bestArea = i, enl, area
			}
		}
		b := best & (maxE - 1)
		// The child's subtree gains exactly this rectangle, so the union is
		// its exact new bounding rectangle.
		nd.x0[b] = min(nd.x0[b], x0)
		nd.y0[b] = min(nd.y0[b], y0)
		nd.x1[b] = max(nd.x1[b], x1)
		nd.y1[b] = max(nd.y1[b], y1)
		t.path[d] = cur
		t.pos[d] = int32(b)
		d++
		cur = nd.ch[b]
	}
	nd := t.nd(cur)
	if nd.n < maxE {
		j := nd.n & (maxE - 1)
		nd.x0[j], nd.y0[j], nd.x1[j], nd.y1[j], nd.ch[j] = x0, y0, x1, y1, v
		nd.n++
		return
	}
	newIdx := t.split(cur, x0, y0, x1, y1, v)
	for {
		cn := t.nd(cur)
		nn := t.nd(newIdx)
		if d == 0 {
			r := t.alloc(cn.level + 1)
			rn := t.nd(r)
			rn.x0[0], rn.y0[0], rn.x1[0], rn.y1[0] = bbox(cn)
			rn.ch[0] = cur
			rn.x0[1], rn.y0[1], rn.x1[1], rn.y1[1] = bbox(nn)
			rn.ch[1] = newIdx
			rn.n = 2
			t.root = r
			return
		}
		d--
		p := t.path[d]
		pi := t.pos[d] & (maxE - 1)
		pn := t.nd(p)
		pn.x0[pi], pn.y0[pi], pn.x1[pi], pn.y1[pi] = bbox(cn)
		bx0, by0, bx1, by1 := bbox(nn)
		if pn.n < maxE {
			j := pn.n & (maxE - 1)
			pn.x0[j], pn.y0[j], pn.x1[j], pn.y1[j], pn.ch[j] = bx0, by0, bx1, by1, newIdx
			pn.n++
			return
		}
		newIdx = t.split(p, bx0, by0, bx1, by1, newIdx)
		cur = p
	}
}

// split distributes the 16 entries of node idx plus the extra entry over
// idx and a new node at the same level (quadratic split), and returns the
// new node.
func (t *RTree) split(idx int32, ex0, ey0, ex1, ey1, ev int32) int32 {
	const N = maxE + 1
	a := t.nd(idx)
	newIdx := t.alloc(a.level)
	b := t.nd(newIdx)

	var X0, Y0, X1, Y1 [N]int64
	var V [N]int32
	var area [N]int64
	for i := 0; i < maxE; i++ {
		X0[i], Y0[i], X1[i], Y1[i] = int64(a.x0[i]), int64(a.y0[i]), int64(a.x1[i]), int64(a.y1[i])
		V[i] = a.ch[i]
	}
	X0[maxE], Y0[maxE], X1[maxE], Y1[maxE] = int64(ex0), int64(ey0), int64(ex1), int64(ey1)
	V[maxE] = ev
	for i := 0; i < N; i++ {
		area[i] = (X1[i] - X0[i]) * (Y1[i] - Y0[i])
	}

	// PickSeeds.
	s1, s2 := 0, 1
	bestD := int64(math.MinInt64)
	for i := 0; i < N-1; i++ {
		ax0, ay0, ax1, ay1, aa := X0[i], Y0[i], X1[i], Y1[i], area[i]
		for j := i + 1; j < N; j++ {
			dd := (max(ax1, X1[j])-min(ax0, X0[j]))*(max(ay1, Y1[j])-min(ay0, Y0[j])) - aa - area[j]
			if dd > bestD {
				bestD, s1, s2 = dd, i, j
			}
		}
	}

	var assigned [N]bool
	assigned[s1] = true
	assigned[s2] = true
	a.n, b.n = 0, 0
	put := func(nd *node, i int) {
		j := nd.n & (maxE - 1)
		nd.x0[j], nd.y0[j], nd.x1[j], nd.y1[j], nd.ch[j] = int32(X0[i]), int32(Y0[i]), int32(X1[i]), int32(Y1[i]), V[i]
		nd.n++
	}
	put(a, s1)
	put(b, s2)
	g1x0, g1y0, g1x1, g1y1 := X0[s1], Y0[s1], X1[s1], Y1[s1]
	g2x0, g2y0, g2x1, g2y1 := X0[s2], Y0[s2], X1[s2], Y1[s2]
	c1, c2 := 1, 1
	remaining := N - 2
	for remaining > 0 {
		if c1+remaining <= minE || c2+remaining <= minE {
			target := a
			if c2+remaining <= minE {
				target = b
			}
			for i := 0; i < N; i++ {
				if !assigned[i] {
					put(target, i)
				}
			}
			break
		}
		area1 := (g1x1 - g1x0) * (g1y1 - g1y0)
		area2 := (g2x1 - g2x0) * (g2y1 - g2y0)
		bi := -1
		bestDiff := int64(-1)
		var bd1, bd2 int64
		for i := 0; i < N; i++ {
			if assigned[i] {
				continue
			}
			d1 := (max(g1x1, X1[i])-min(g1x0, X0[i]))*(max(g1y1, Y1[i])-min(g1y0, Y0[i])) - area1
			d2 := (max(g2x1, X1[i])-min(g2x0, X0[i]))*(max(g2y1, Y1[i])-min(g2y0, Y0[i])) - area2
			diff := d1 - d2
			if diff < 0 {
				diff = -diff
			}
			if diff > bestDiff {
				bestDiff, bi, bd1, bd2 = diff, i, d1, d2
			}
		}
		toFirst := false
		if bd1 != bd2 {
			toFirst = bd1 < bd2
		} else if area1 != area2 {
			toFirst = area1 < area2
		} else {
			toFirst = c1 <= c2
		}
		assigned[bi] = true
		remaining--
		if toFirst {
			put(a, bi)
			c1++
			g1x0, g1y0 = min(g1x0, X0[bi]), min(g1y0, Y0[bi])
			g1x1, g1y1 = max(g1x1, X1[bi]), max(g1y1, Y1[bi])
		} else {
			put(b, bi)
			c2++
			g2x0, g2y0 = min(g2x0, X0[bi]), min(g2y0, Y0[bi])
			g2x1, g2y1 = max(g2x1, X1[bi]), max(g2y1, Y1[bi])
		}
	}
	return newIdx
}

func (t *RTree) Remove(x0, y0, x1, y1, id int32) bool {
	if t.size == 0 {
		return false
	}
	// Find the leaf: depth-first over subtrees whose rectangle contains the
	// query rectangle, keeping the path.
	d := 0
	t.path[0] = t.root
	t.pos[0] = 0
	found := -1
	for d >= 0 {
		nd := t.nd(t.path[d])
		cnt := int(nd.n)
		if nd.level == 0 {
			for i := 0; i < cnt; i++ {
				j := i & (maxE - 1)
				if nd.ch[j] == id && nd.x0[j] == x0 && nd.y0[j] == y0 && nd.x1[j] == x1 && nd.y1[j] == y1 {
					found = j
					break
				}
			}
			if found >= 0 {
				break
			}
			d--
			continue
		}
		i := int(t.pos[d])
		for ; i < cnt; i++ {
			j := i & (maxE - 1)
			if nd.x0[j] <= x0 && nd.y0[j] <= y0 && nd.x1[j] >= x1 && nd.y1[j] >= y1 {
				break
			}
		}
		if i < cnt {
			t.pos[d] = int32(i + 1)
			d++
			t.path[d] = nd.ch[i&(maxE-1)]
			t.pos[d] = 0
		} else {
			d--
		}
	}
	if d < 0 {
		return false
	}

	// Remove the entry from the leaf.
	leaf := t.nd(t.path[d])
	last := (leaf.n - 1) & (maxE - 1)
	leaf.x0[found], leaf.y0[found], leaf.x1[found], leaf.y1[found], leaf.ch[found] =
		leaf.x0[last], leaf.y0[last], leaf.x1[last], leaf.y1[last], leaf.ch[last]
	leaf.n--
	t.size--

	// Condense the tree.
	t.setAside = t.setAside[:0]
	for l := d; l > 0; l-- {
		ni := t.path[l]
		nd := t.nd(ni)
		p := t.nd(t.path[l-1])
		pi := (t.pos[l-1] - 1) & (maxE - 1)
		if nd.n < minE {
			pl := (p.n - 1) & (maxE - 1)
			p.x0[pi], p.y0[pi], p.x1[pi], p.y1[pi], p.ch[pi] = p.x0[pl], p.y0[pl], p.x1[pl], p.y1[pl], p.ch[pl]
			p.n--
			t.setAside = append(t.setAside, ni)
		} else {
			bx0, by0, bx1, by1 := bbox(nd)
			if bx0 == p.x0[pi] && by0 == p.y0[pi] && bx1 == p.x1[pi] && by1 == p.y1[pi] {
				// Nothing above changes.
				break
			}
			p.x0[pi], p.y0[pi], p.x1[pi], p.y1[pi] = bx0, by0, bx1, by1
		}
	}

	// Reinsert the entries of the removed nodes at their levels.
	for k := 0; k < len(t.setAside); k++ {
		ni := t.setAside[k]
		nd := t.nd(ni)
		cnt := int(nd.n)
		lvl := nd.level
		var ex0, ey0, ex1, ey1, ev [maxE]int32
		ex0, ey0, ex1, ey1, ev = nd.x0, nd.y0, nd.x1, nd.y1, nd.ch
		t.freeNode(ni)
		for i := 0; i < cnt; i++ {
			j := i & (maxE - 1)
			t.insertAt(ex0[j], ey0[j], ex1[j], ey1[j], ev[j], lvl)
		}
	}

	// Shorten the tree.
	for {
		r := t.nd(t.root)
		if r.level == 0 || r.n != 1 {
			break
		}
		old := t.root
		t.root = r.ch[0]
		t.freeNode(old)
	}
	return true
}

func (t *RTree) Search(x0, y0, x1, y1 int32, outIDs []int32) int {
	if t.size == 0 {
		return 0
	}
	total := 0
	capn := len(outIDs)
	st := &t.stack
	st[0] = t.root
	sp := 1
	for sp > 0 {
		sp--
		nd := t.nd(st[sp&(stackSize-1)])
		cnt := int(nd.n)
		if nd.level == 0 {
			for i := 0; i < cnt; i++ {
				j := i & (maxE - 1)
				if nd.x0[j] <= x1 && x0 <= nd.x1[j] && nd.y0[j] <= y1 && y0 <= nd.y1[j] {
					if total < capn {
						outIDs[total] = nd.ch[j]
					}
					total++
				}
			}
		} else {
			for i := 0; i < cnt; i++ {
				j := i & (maxE - 1)
				if nd.x0[j] <= x1 && x0 <= nd.x1[j] && nd.y0[j] <= y1 && y0 <= nd.y1[j] {
					st[sp&(stackSize-1)] = nd.ch[j]
					sp++
				}
			}
		}
	}
	return total
}

func dist2(x, y, x0, y0, x1, y1 int32) uint64 {
	dx := max(x0-x, 0, x-x1)
	dy := max(y0-y, 0, y-y1)
	return uint64(int64(dx)*int64(dx) + int64(dy)*int64(dy))
}

func (t *RTree) Nearest(x, y int32, k int, outIDs []int32) int {
	if k <= 0 || t.size == 0 {
		return 0
	}
	if k > t.size {
		k = t.size
	}
	if cap(t.resD) < k {
		t.resD = make([]uint64, k)
		t.resI = make([]int32, k)
	}
	resD := t.resD[:k]
	resI := t.resI[:k]
	cnt := 0
	worst := uint64(math.MaxUint64) // distance of resD[k-1] once full
	h := t.heap[:0]
	h = append(h, hitem{0, t.root})
	for len(h) > 0 {
		top := h[0]
		if top.d > worst {
			break
		}
		// Pop.
		nlen := len(h) - 1
		lastItem := h[nlen]
		h = h[:nlen]
		if nlen > 0 {
			i := 0
			for {
				c := 2*i + 1
				if c >= nlen {
					break
				}
				if c+1 < nlen && h[c+1].d < h[c].d {
					c++
				}
				if h[c].d >= lastItem.d {
					break
				}
				h[i] = h[c]
				i = c
			}
			h[i] = lastItem
		}

		nd := t.nd(top.n)
		n := int(nd.n)
		if nd.level == 0 {
			for i := 0; i < n; i++ {
				j := i & (maxE - 1)
				dd := dist2(x, y, nd.x0[j], nd.y0[j], nd.x1[j], nd.y1[j])
				if dd > worst {
					continue
				}
				id := nd.ch[j]
				var p int
				if cnt < k {
					p = cnt
					cnt++
				} else {
					if dd == worst && id > resI[k-1] {
						continue
					}
					p = k - 1
				}
				for p > 0 && (resD[p-1] > dd || (resD[p-1] == dd && resI[p-1] > id)) {
					resD[p] = resD[p-1]
					resI[p] = resI[p-1]
					p--
				}
				resD[p] = dd
				resI[p] = id
				if cnt == k {
					worst = resD[k-1]
				}
			}
		} else {
			for i := 0; i < n; i++ {
				j := i & (maxE - 1)
				dd := dist2(x, y, nd.x0[j], nd.y0[j], nd.x1[j], nd.y1[j])
				if dd > worst {
					continue
				}
				// Push.
				it := hitem{dd, nd.ch[j]}
				h = append(h, it)
				c := len(h) - 1
				for c > 0 {
					p := (c - 1) >> 1
					if h[p].d <= dd {
						break
					}
					h[c] = h[p]
					c = p
				}
				h[c] = it
			}
		}
	}
	t.heap = h
	copy(outIDs[:cnt], resI[:cnt])
	return cnt
}

func (t *RTree) Len() int { return t.size }

func (t *RTree) Height() int {
	if t.size == 0 {
		return 0
	}
	return int(t.nd(t.root).level) + 1
}

func (t *RTree) NodeCount() int {
	if t.size == 0 {
		return 0
	}
	return t.countNodes(t.root)
}

func (t *RTree) countNodes(i int32) int {
	nd := t.nd(i)
	if nd.level == 0 {
		return 1
	}
	c := 1
	for j := 0; j < int(nd.n); j++ {
		c += t.countNodes(nd.ch[j])
	}
	return c
}
