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

// Array-based binary min-heap of (Int64 key, Int64 value) entries.
//
// Representation: each entry is stored as one Int128 whose high 64 bits are
// the key (signed) and whose low 64 bits are the value with its sign bit
// flipped. Signed Int128 order is then exactly the (key, value) lexicographic
// order, so every comparison is a single 128-bit compare (cmp + sbcs on
// arm64) and every move is one 16-byte load/store.
//
// Layout: tree position i lives at memory index i + 1 (index 0 is padding),
// i.e. a 1-based heap: children of memory index m are 2m and 2m + 1, parent is
// m >> 1. The buffer is 128-byte aligned, so each sibling pair (2m, 2m + 1)
// occupies one aligned 32-byte block and never straddles a cache line.
final class Heap {
    @exclusivity(unchecked) private var base: UnsafeMutablePointer<Int128>
    @exclusivity(unchecked) private var n: Int     // number of entries
    @exclusivity(unchecked) private var cap: Int   // allocated slots (incl. padding slot 0)

    private static let minCap = 64

    @inline(__always)
    private static func alloc(_ slots: Int) -> UnsafeMutablePointer<Int128> {
        var raw: UnsafeMutableRawPointer? = nil
        let bytes = slots &* MemoryLayout<Int128>.stride
        if posix_memalign(&raw, 128, bytes) != 0 || raw == nil {
            fatalError("Heap: out of memory")
        }
        return raw!.bindMemory(to: Int128.self, capacity: slots)
    }

    @inline(__always)
    private static func encode(_ k: Int64, _ v: Int64) -> Int128 {
        (Int128(k) &<< 64) | Int128(UInt64(bitPattern: v ^ Int64.min))
    }

    @inline(__always)
    private static func decode(_ x: Int128) -> (key: Int64, value: Int64) {
        (key: Int64(truncatingIfNeeded: x &>> 64),
         value: Int64(bitPattern: UInt64(truncatingIfNeeded: x)) ^ Int64.min)
    }

    init() {
        base = Heap.alloc(Heap.minCap)
        n = 0
        cap = Heap.minCap
    }

    init(keys: UnsafePointer<Int64>, values: UnsafePointer<Int64>, count: Int) {
        let c = max(count &+ 1, Heap.minCap)
        let b = Heap.alloc(c)
        var i = 0
        while i < count {
            (b + (i &+ 1)).initialize(to: Heap.encode(keys[i], values[i]))
            i &+= 1
        }
        base = b
        n = count
        cap = c
        // Floyd's bottom-up heap construction: O(count).
        var m = count >> 1
        while m >= 1 {
            Heap.siftDown(b, count, b[m], m)
            m &-= 1
        }
    }

    deinit {
        free(base)
    }

    @inline(never)
    private func grow() {
        let newCap = cap &* 2
        let nb = Heap.alloc(newCap)
        memcpy(nb, base, (n &+ 1) &* MemoryLayout<Int128>.stride)
        free(base)
        base = nb
        cap = newCap
    }

    // Top-down sift-down of x starting at hole m in a heap of `cnt` entries.
    @inline(__always)
    private static func siftDown(_ b: UnsafeMutablePointer<Int128>, _ cnt: Int,
                                 _ x: Int128, _ start: Int) {
        var m = start
        while true {
            var c = m &<< 1
            if c >= cnt {
                if c == cnt {
                    let cv = b[c]
                    if cv < x { b[m] = cv; m = c }
                }
                break
            }
            let l = b[c]
            let r = b[c | 1]
            let pick = r < l
            c |= pick ? 1 : 0
            let cv = pick ? r : l
            if !(cv < x) { break }
            b[m] = cv
            m = c
        }
        b[m] = x
    }

    @inline(__always)
    func push(_ key: Int64, _ value: Int64) {
        let x = Heap.encode(key, value)
        var m = n &+ 1
        if m >= cap { grow() }
        n = m
        let b = base
        while m > 1 {
            let p = m &>> 1
            let pv = b[p]
            if !(x < pv) { break }
            b[m] = pv
            m = p
        }
        b[m] = x
    }

    @inline(__always)
    func peek() -> (key: Int64, value: Int64)? {
        if n == 0 { return nil }
        return Heap.decode(base[1])
    }

    @inline(__always)
    func pop() -> (key: Int64, value: Int64)? {
        let cnt0 = n
        if cnt0 == 0 { return nil }
        let b = base
        let top = b[1]
        let x = b[cnt0]
        let cnt = cnt0 &- 1
        n = cnt
        if cnt == 0 { return Heap.decode(top) }
        // Bottom-up: move the hole from the root down to a leaf along the
        // smaller-child path, then sift the former last entry up from there.
        var m = 1
        var c = 2
        while c < cnt {
            let l = b[c]
            let r = b[c | 1]
            let pick = r < l
            c |= pick ? 1 : 0
            b[m] = pick ? r : l
            m = c
            c = m &<< 1
        }
        if c == cnt {
            b[m] = b[c]
            m = c
        }
        while m > 1 {
            let p = m &>> 1
            let pv = b[p]
            if !(x < pv) { break }
            b[m] = pv
            m = p
        }
        b[m] = x
        return Heap.decode(top)
    }

    @inline(__always)
    func replace(_ key: Int64, _ value: Int64) -> (key: Int64, value: Int64)? {
        let cnt = n
        if cnt == 0 {
            push(key, value)
            return nil
        }
        let b = base
        let top = b[1]
        Heap.siftDown(b, cnt, Heap.encode(key, value), 1)
        return Heap.decode(top)
    }

    @inline(__always)
    func pushPop(_ key: Int64, _ value: Int64) -> (key: Int64, value: Int64) {
        let cnt = n
        let x = Heap.encode(key, value)
        if cnt == 0 { return (key: key, value: value) }
        let b = base
        let top = b[1]
        if !(top < x) { return (key: key, value: value) }
        Heap.siftDown(b, cnt, x, 1)
        return Heap.decode(top)
    }

    var count: Int {
        @inline(__always) get { n }
    }

    func slot(_ i: Int) -> (key: Int64, value: Int64) {
        precondition(i >= 0 && i < n, "slot index out of range")
        return Heap.decode(base[i &+ 1])
    }
}
