// Classic B-tree (CLRS ch. 18), minimum degree t = 16, Int64 -> Int64.
//
// Node layout (raw memory, 128-byte aligned):
//   0   : Int32 key count
//   4   : Int32 leaf flag (1 = leaf)
//   8   : keys[31]      (8 ..< 256: exactly two 128-byte cache lines)
//   256 : vals[31]      (256 ..< 504)
//   512 : children[32]  (internal nodes only, 512 ..< 768)
// Leaves are 512 bytes, internal nodes 768 bytes. Nodes are carved from
// slabs and recycled through per-kind free lists; all slabs are released
// when the tree is destroyed.

#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

typealias NodePtr = UnsafeMutableRawPointer

@usableFromInline let BT_MAXK = 31
@usableFromInline let BT_MINK = 15
@usableFromInline let BT_LEAF_SIZE = 512
@usableFromInline let BT_INTERNAL_SIZE = 768
@usableFromInline let BT_LEAF_SLAB = 64
@usableFromInline let BT_INTERNAL_SLAB = 16
@usableFromInline let BT_STACK = 64

@inline(__always) func nCount(_ n: NodePtr) -> Int {
    Int(n.assumingMemoryBound(to: Int32.self).pointee)
}
@inline(__always) func setCount(_ n: NodePtr, _ c: Int) {
    n.assumingMemoryBound(to: Int32.self).pointee = Int32(truncatingIfNeeded: c)
}
@inline(__always) func isLeaf(_ n: NodePtr) -> Bool {
    (n + 4).assumingMemoryBound(to: Int32.self).pointee != 0
}
@inline(__always) func setLeaf(_ n: NodePtr, _ leaf: Bool) {
    (n + 4).assumingMemoryBound(to: Int32.self).pointee = leaf ? 1 : 0
}
@inline(__always) func keysOf(_ n: NodePtr) -> UnsafeMutablePointer<Int64> {
    (n + 8).assumingMemoryBound(to: Int64.self)
}
@inline(__always) func valsOf(_ n: NodePtr) -> UnsafeMutablePointer<Int64> {
    (n + 256).assumingMemoryBound(to: Int64.self)
}
@inline(__always) func kidsOf(_ n: NodePtr) -> UnsafeMutablePointer<NodePtr> {
    (n + 512).assumingMemoryBound(to: NodePtr.self)
}

@inline(__always) func mmove<T>(_ dst: UnsafeMutablePointer<T>, _ src: UnsafeMutablePointer<T>, _ count: Int) {
    if count > 0 { memmove(dst, src, count &* MemoryLayout<T>.stride) }
}
@inline(__always) func mcopy<T>(_ dst: UnsafeMutablePointer<T>, _ src: UnsafeMutablePointer<T>, _ count: Int) {
    if count > 0 { memcpy(dst, src, count &* MemoryLayout<T>.stride) }
}

// Number of keys in k[0..<n] that are < key (n <= 31). Branch-free search
// over 32 virtual slots; slots >= n are treated as +infinity.
@inline(__always) func lowerBound(_ k: UnsafeMutablePointer<Int64>, _ n: Int, _ key: Int64) -> Int {
    var b = 0
    if k[15] < key && 15 < n { b = 16 }
    if k[b &+ 7] < key && b &+ 7 < n { b &+= 8 }
    if k[b &+ 3] < key && b &+ 3 < n { b &+= 4 }
    if k[b &+ 1] < key && b &+ 1 < n { b &+= 2 }
    if k[b] < key && b < n { b &+= 1 }
    return b
}

struct BTreeState {
    var root: NodePtr? = nil
    var count: Int = 0
    var height: Int = 0
    var freeLeaf: NodePtr? = nil
    var freeInternal: NodePtr? = nil
    var leafCur: NodePtr? = nil
    var leafLeft: Int = 0
    var intCur: NodePtr? = nil
    var intLeft: Int = 0
    var slabs: UnsafeMutablePointer<NodePtr>? = nil
    var slabCount: Int = 0
    var slabCap: Int = 0
}

final class BTree {
    private let st: UnsafeMutablePointer<BTreeState>
    private let pathN: UnsafeMutablePointer<NodePtr>
    private let pathI: UnsafeMutablePointer<Int>

    init() {
        st = UnsafeMutablePointer<BTreeState>.allocate(capacity: 1)
        st.initialize(to: BTreeState())
        pathN = UnsafeMutablePointer<NodePtr>.allocate(capacity: BT_STACK)
        pathI = UnsafeMutablePointer<Int>.allocate(capacity: BT_STACK)
    }

    deinit {
        let s = st
        if let sl = s.pointee.slabs {
            for j in 0..<s.pointee.slabCount { free(sl[j]) }
            free(sl)
        }
        st.deinitialize(count: 1)
        st.deallocate()
        pathN.deallocate()
        pathI.deallocate()
    }

    var count: Int { st.pointee.count }

    func height() -> Int { st.pointee.height }

    // ------------------------------------------------------------ memory

    @inline(never)
    private func newSlab(_ bytes: Int) -> NodePtr {
        var raw: UnsafeMutableRawPointer? = nil
        if posix_memalign(&raw, 128, bytes) != 0 || raw == nil { fatalError("out of memory") }
        let s = st
        if s.pointee.slabCount == s.pointee.slabCap {
            let nc = max(16, s.pointee.slabCap * 2)
            let p = realloc(s.pointee.slabs, nc * MemoryLayout<NodePtr>.stride)!
            s.pointee.slabs = p.assumingMemoryBound(to: NodePtr.self)
            s.pointee.slabCap = nc
        }
        s.pointee.slabs![s.pointee.slabCount] = raw!
        s.pointee.slabCount += 1
        return raw!
    }

    @inline(__always)
    private func allocLeaf() -> NodePtr {
        let s = st
        let n: NodePtr
        if let f = s.pointee.freeLeaf {
            s.pointee.freeLeaf = f.load(fromByteOffset: 8, as: NodePtr?.self)
            n = f
        } else {
            if s.pointee.leafLeft == 0 {
                s.pointee.leafCur = newSlab(BT_LEAF_SIZE * BT_LEAF_SLAB)
                s.pointee.leafLeft = BT_LEAF_SLAB
            }
            n = s.pointee.leafCur!
            s.pointee.leafCur = n + BT_LEAF_SIZE
            s.pointee.leafLeft -= 1
        }
        setLeaf(n, true)
        return n
    }

    @inline(__always)
    private func allocInternal() -> NodePtr {
        let s = st
        let n: NodePtr
        if let f = s.pointee.freeInternal {
            s.pointee.freeInternal = f.load(fromByteOffset: 8, as: NodePtr?.self)
            n = f
        } else {
            if s.pointee.intLeft == 0 {
                s.pointee.intCur = newSlab(BT_INTERNAL_SIZE * BT_INTERNAL_SLAB)
                s.pointee.intLeft = BT_INTERNAL_SLAB
            }
            n = s.pointee.intCur!
            s.pointee.intCur = n + BT_INTERNAL_SIZE
            s.pointee.intLeft -= 1
        }
        setLeaf(n, false)
        return n
    }

    @inline(__always)
    private func freeNode(_ n: NodePtr) {
        let s = st
        if isLeaf(n) {
            n.storeBytes(of: s.pointee.freeLeaf, toByteOffset: 8, as: NodePtr?.self)
            s.pointee.freeLeaf = n
        } else {
            n.storeBytes(of: s.pointee.freeInternal, toByteOffset: 8, as: NodePtr?.self)
            s.pointee.freeInternal = n
        }
    }

    // ------------------------------------------------------------ get

    func get(_ key: Int64) -> Int64? {
        guard var node = st.pointee.root else { return nil }
        while true {
            let n = nCount(node)
            let k = keysOf(node)
            let i = lowerBound(k, n, key)
            if i < n && k[i] == key { return valsOf(node)[i] }
            if isLeaf(node) { return nil }
            node = kidsOf(node)[i]
        }
    }

    // ------------------------------------------------------------ insert

    func insert(_ key: Int64, _ value: Int64) -> Bool {
        let s = st
        guard var node = s.pointee.root else {
            let l = allocLeaf()
            keysOf(l)[0] = key
            valsOf(l)[0] = value
            setCount(l, 1)
            s.pointee.root = l
            s.pointee.height = 1
            s.pointee.count = 1
            return true
        }
        let pathN = self.pathN, pathI = self.pathI
        var depth = 0
        var i: Int
        while true {
            let n = nCount(node)
            let k = keysOf(node)
            i = lowerBound(k, n, key)
            if i < n && k[i] == key {
                valsOf(node)[i] = value
                return false
            }
            if isLeaf(node) { break }
            pathN[depth] = node
            pathI[depth] = i
            depth &+= 1
            node = kidsOf(node)[i]
        }
        s.pointee.count &+= 1
        let n = nCount(node)
        if n < BT_MAXK {
            let k = keysOf(node), v = valsOf(node)
            mmove(k + i + 1, k + i, n - i)
            mmove(v + i + 1, v + i, n - i)
            k[i] = key
            v[i] = value
            setCount(node, n + 1)
            return true
        }
        var (mk, mv, r) = splitInsert(node, i, key, value, nil, true)
        while depth > 0 {
            depth &-= 1
            let p = pathN[depth]
            let pi = pathI[depth]
            let pn = nCount(p)
            if pn < BT_MAXK {
                let k = keysOf(p), v = valsOf(p), c = kidsOf(p)
                mmove(k + pi + 1, k + pi, pn - pi)
                mmove(v + pi + 1, v + pi, pn - pi)
                mmove(c + pi + 2, c + pi + 1, pn - pi)
                k[pi] = mk
                v[pi] = mv
                c[pi + 1] = r
                setCount(p, pn + 1)
                return true
            }
            (mk, mv, r) = splitInsert(p, pi, mk, mv, r, false)
        }
        let nr = allocInternal()
        keysOf(nr)[0] = mk
        valsOf(nr)[0] = mv
        kidsOf(nr)[0] = s.pointee.root!
        kidsOf(nr)[1] = r
        setCount(nr, 1)
        s.pointee.root = nr
        s.pointee.height &+= 1
        return true
    }

    // Split a full node (31 keys) while inserting (key, val) at position i
    // and, for internal nodes, child `rc` at position i + 1. The node keeps
    // 16 keys, the new right node gets 15; returns the median and right node.
    @inline(never)
    private func splitInsert(_ node: NodePtr, _ i: Int, _ key: Int64, _ val: Int64,
                             _ rc: NodePtr?, _ leaf: Bool) -> (Int64, Int64, NodePtr) {
        let r = leaf ? allocLeaf() : allocInternal()
        let k = keysOf(node), v = valsOf(node)
        let rk = keysOf(r), rv = valsOf(r)
        let mk: Int64, mv: Int64
        if i < 16 {
            mcopy(rk, k + 16, 15)
            mcopy(rv, v + 16, 15)
            mk = k[15]
            mv = v[15]
            mmove(k + i + 1, k + i, 15 - i)
            mmove(v + i + 1, v + i, 15 - i)
            k[i] = key
            v[i] = val
            if !leaf {
                let c = kidsOf(node), rcs = kidsOf(r)
                mcopy(rcs, c + 16, 16)
                mmove(c + i + 2, c + i + 1, 15 - i)
                c[i + 1] = rc!
            }
        } else if i == 16 {
            mcopy(rk, k + 16, 15)
            mcopy(rv, v + 16, 15)
            mk = key
            mv = val
            if !leaf {
                let c = kidsOf(node), rcs = kidsOf(r)
                rcs[0] = rc!
                mcopy(rcs + 1, c + 17, 15)
            }
        } else {
            let j = i - 17
            mcopy(rk, k + 17, j)
            mcopy(rv, v + 17, j)
            rk[j] = key
            rv[j] = val
            mcopy(rk + j + 1, k + i, 31 - i)
            mcopy(rv + j + 1, v + i, 31 - i)
            mk = k[16]
            mv = v[16]
            if !leaf {
                let c = kidsOf(node), rcs = kidsOf(r)
                mcopy(rcs, c + 17, j + 1)
                rcs[j + 1] = rc!
                mcopy(rcs + j + 2, c + i + 1, 31 - i)
            }
        }
        setCount(node, 16)
        setCount(r, 15)
        return (mk, mv, r)
    }

    // ------------------------------------------------------------ remove

    func remove(_ key: Int64) -> Bool {
        let s = st
        guard var node = s.pointee.root else { return false }
        let pathN = self.pathN, pathI = self.pathI
        var depth = 0
        var i: Int
        while true {
            let n = nCount(node)
            let k = keysOf(node)
            i = lowerBound(k, n, key)
            if i < n && k[i] == key { break }
            if isLeaf(node) { return false }
            pathN[depth] = node
            pathI[depth] = i
            depth &+= 1
            node = kidsOf(node)[i]
        }
        if !isLeaf(node) {
            // Replace with the predecessor, then delete that from its leaf.
            let target = node, ti = i
            pathN[depth] = node
            pathI[depth] = i
            depth &+= 1
            var c = kidsOf(node)[i]
            while !isLeaf(c) {
                let cn = nCount(c)
                pathN[depth] = c
                pathI[depth] = cn
                depth &+= 1
                c = kidsOf(c)[cn]
            }
            let cn = nCount(c)
            keysOf(target)[ti] = keysOf(c)[cn - 1]
            valsOf(target)[ti] = valsOf(c)[cn - 1]
            node = c
            i = cn - 1
        }
        let n = nCount(node)
        let k = keysOf(node), v = valsOf(node)
        mmove(k + i, k + i + 1, n - 1 - i)
        mmove(v + i, v + i + 1, n - 1 - i)
        setCount(node, n - 1)
        s.pointee.count &-= 1
        if n - 1 >= BT_MINK { return true }
        if depth == 0 {
            if n - 1 == 0 {
                freeNode(node)
                s.pointee.root = nil
                s.pointee.height = 0
            }
            return true
        }
        rebalance(node, depth)
        return true
    }

    @inline(never)
    private func rebalance(_ start: NodePtr, _ startDepth: Int) {
        let s = st
        var x = start
        var d = startDepth
        while d > 0 {
            let xn = nCount(x)
            if xn >= BT_MINK { return }
            d &-= 1
            let p = pathN[d]
            let ci = pathI[d]
            let pn = nCount(p)
            let leaf = isLeaf(x)
            let pc = kidsOf(p)
            if ci > 0 {
                let l = pc[ci - 1]
                let ln = nCount(l)
                if ln > BT_MINK {
                    rotateRight(p, ci - 1, l, ln, x, xn, leaf)
                    return
                }
            }
            if ci < pn {
                let r = pc[ci + 1]
                let rn = nCount(r)
                if rn > BT_MINK {
                    rotateLeft(p, ci, x, xn, r, rn, leaf)
                    return
                }
            }
            if ci > 0 {
                merge(p, pn, ci - 1, pc[ci - 1], x, leaf)
            } else {
                merge(p, pn, ci, x, pc[ci + 1], leaf)
            }
            x = p
        }
        let root = s.pointee.root!
        if nCount(root) == 0 && !isLeaf(root) {
            s.pointee.root = kidsOf(root)[0]
            s.pointee.height &-= 1
            freeNode(root)
        }
    }

    // Move keys from left sibling l (separator p.keys[si]) into x.
    @inline(__always)
    private func rotateRight(_ p: NodePtr, _ si: Int, _ l: NodePtr, _ ln: Int,
                             _ x: NodePtr, _ xn: Int, _ leaf: Bool) {
        let m = (ln - xn) >> 1
        let xk = keysOf(x), xv = valsOf(x)
        let lk = keysOf(l), lv = valsOf(l)
        let pk = keysOf(p), pv = valsOf(p)
        mmove(xk + m, xk, xn)
        mmove(xv + m, xv, xn)
        xk[m - 1] = pk[si]
        xv[m - 1] = pv[si]
        mcopy(xk, lk + (ln - m + 1), m - 1)
        mcopy(xv, lv + (ln - m + 1), m - 1)
        pk[si] = lk[ln - m]
        pv[si] = lv[ln - m]
        if !leaf {
            let xc = kidsOf(x), lc = kidsOf(l)
            mmove(xc + m, xc, xn + 1)
            mcopy(xc, lc + (ln - m + 1), m)
        }
        setCount(l, ln - m)
        setCount(x, xn + m)
    }

    // Move keys from right sibling r (separator p.keys[si]) into x.
    @inline(__always)
    private func rotateLeft(_ p: NodePtr, _ si: Int, _ x: NodePtr, _ xn: Int,
                            _ r: NodePtr, _ rn: Int, _ leaf: Bool) {
        let m = (rn - xn) >> 1
        let xk = keysOf(x), xv = valsOf(x)
        let rk = keysOf(r), rv = valsOf(r)
        let pk = keysOf(p), pv = valsOf(p)
        xk[xn] = pk[si]
        xv[xn] = pv[si]
        mcopy(xk + xn + 1, rk, m - 1)
        mcopy(xv + xn + 1, rv, m - 1)
        pk[si] = rk[m - 1]
        pv[si] = rv[m - 1]
        mmove(rk, rk + m, rn - m)
        mmove(rv, rv + m, rn - m)
        if !leaf {
            let xc = kidsOf(x), rc = kidsOf(r)
            mcopy(xc + xn + 1, rc, m)
            mmove(rc, rc + m, rn - m + 1)
        }
        setCount(x, xn + m)
        setCount(r, rn - m)
    }

    // Merge child si+1 (r) into child si (l) with separator p.keys[si].
    @inline(__always)
    private func merge(_ p: NodePtr, _ pn: Int, _ si: Int, _ l: NodePtr, _ r: NodePtr, _ leaf: Bool) {
        let ln = nCount(l), rn = nCount(r)
        let lk = keysOf(l), lv = valsOf(l)
        let pk = keysOf(p), pv = valsOf(p)
        lk[ln] = pk[si]
        lv[ln] = pv[si]
        mcopy(lk + ln + 1, keysOf(r), rn)
        mcopy(lv + ln + 1, valsOf(r), rn)
        if !leaf {
            mcopy(kidsOf(l) + ln + 1, kidsOf(r), rn + 1)
        }
        setCount(l, ln + 1 + rn)
        mmove(pk + si, pk + si + 1, pn - 1 - si)
        mmove(pv + si, pv + si + 1, pn - 1 - si)
        let pc = kidsOf(p)
        mmove(pc + si + 1, pc + si + 2, pn - 1 - si)
        setCount(p, pn - 1)
        freeNode(r)
    }

    // ------------------------------------------------------------ range

    func range(_ lo: Int64, _ hi: Int64,
               _ outKeys: UnsafeMutablePointer<Int64>,
               _ outVals: UnsafeMutablePointer<Int64>,
               _ limit: Int) -> Int {
        if lo > hi || limit <= 0 { return 0 }
        guard var node = st.pointee.root else { return 0 }
        let pathN = self.pathN, pathI = self.pathI
        var depth = 0
        while !isLeaf(node) {
            let i = lowerBound(keysOf(node), nCount(node), lo)
            pathN[depth] = node
            pathI[depth] = i
            depth &+= 1
            node = kidsOf(node)[i]
        }
        var i = lowerBound(keysOf(node), nCount(node), lo)
        var out = 0
        while true {
            let n = nCount(node)
            if i < n {
                let k = keysOf(node), v = valsOf(node)
                let take = min(n - i, limit - out)
                if k[i + take - 1] > hi {
                    var e = i
                    while k[e] <= hi { e &+= 1 }
                    let c = e - i
                    mcopy(outKeys + out, k + i, c)
                    mcopy(outVals + out, v + i, c)
                    return out + c
                }
                mcopy(outKeys + out, k + i, take)
                mcopy(outVals + out, v + i, take)
                out &+= take
                if out == limit { return out }
            }
            // Ascend to the next separator, emit it, descend to the next leaf.
            while true {
                if depth == 0 { return out }
                depth &-= 1
                let p = pathN[depth]
                let pi = pathI[depth]
                if pi < nCount(p) {
                    let pk = keysOf(p)[pi]
                    if pk > hi { return out }
                    outKeys[out] = pk
                    outVals[out] = valsOf(p)[pi]
                    out &+= 1
                    if out == limit { return out }
                    pathI[depth] = pi + 1
                    depth &+= 1
                    node = kidsOf(p)[pi + 1]
                    while !isLeaf(node) {
                        pathN[depth] = node
                        pathI[depth] = 0
                        depth &+= 1
                        node = kidsOf(node)[0]
                    }
                    i = 0
                    break
                }
            }
        }
    }
}
