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

final class SkipList {
    private static let maxHeight = 32
    private static let headerIdx: UInt32 = 0x8000_0000
    private static let upperFlag: UInt32 = 0x8000_0000
    private static let indexMask: UInt32 = 0x7FFF_FFFF

    // Layout of every node (all sizes are multiples of 8 bytes):
    //   offset 0:  val: Int64      (8 bytes)  [also nextFree: UInt32 when on free list]
    //   offset 8:  key: Int64      (8 bytes)
    //   offset 16: next[0..<h]: UInt32 (4 * h bytes)
    //
    // upperBase layout:
    //   bytes   0..<144 (18 units): header node (32 forward links at offset 16..<144)
    //   bytes 144..<272 (16 units): scratch pred[0..<32] array for insert()
    //   bytes 272...             : nodes of height >= 5 (keeps upper levels dense in L2)
    //
    // lowerBase layout:
    //   bytes   0..<8   ( 1 unit ): reserved so index 0 is NULL
    //   bytes   8...             : nodes of height 1..4
    private static let predByteOffset = 144
    private static let upperInitialUsed = 34 // (144 + 128) / 8

    // Hot fields grouped into a single 128-byte cache line.
    private var lowerBase: UnsafeMutableRawPointer
    private var upperBase: UnsafeMutableRawPointer
    private var topLevel: Int = -1
    private(set) var count: Int = 0
    private var rngState: UInt64 = 0x243F6A8885A308D3
    private var lowerUsed: Int = 1
    private var lowerCap: Int = 512
    private var upperUsed: Int = SkipList.upperInitialUsed
    private var upperCap: Int = 256

    // Per-size-class intrusive free lists:
    //   free0: h 1..2  (24B =  3 units, lowerBase)
    //   free1: h 3..4  (32B =  4 units, lowerBase)
    //   free2: h 5..6  (40B =  5 units, upperBase)
    //   free3: h 7..8  (48B =  6 units, upperBase)
    //   free4: h 9..12 (64B =  8 units, upperBase)
    //   free5: h 13..16(80B = 10 units, upperBase)
    //   free6: h 17..24(112B= 14 units, upperBase)
    //   free7: h 25..32(144B= 18 units, upperBase)
    private var free0: UInt32 = 0
    private var free1: UInt32 = 0
    private var free2: UInt32 = 0
    private var free3: UInt32 = 0
    private var free4: UInt32 = 0
    private var free5: UInt32 = 0
    private var free6: UInt32 = 0
    private var free7: UInt32 = 0

    init() {
        guard let lo = malloc(512 &* 8), let hi = malloc(256 &* 8) else {
            fatalError("SkipList allocation failed")
        }
        memset(hi, 0, 144)
        self.lowerBase = lo
        self.upperBase = hi
    }

    deinit {
        free(lowerBase)
        free(upperBase)
    }

    // MARK: - Pointer & Pool Helpers

    @inline(__always)
    private func ptr(_ idx: UInt32) -> UnsafeMutableRawPointer {
        let base = Int32(bitPattern: idx) < 0 ? upperBase : lowerBase
        return base.advanced(by: Int(idx & SkipList.indexMask) &<< 3)
    }

    @inline(__always)
    private func randomHeight() -> Int {
        // SplitMix64 step -> geometric(p = 1/2) capped at 32.
        rngState &+= 0x9E3779B97F4A7C15
        var z = rngState
        z = (z ^ (z &>> 30)) &* 0xBF58476D1CE4E5B9
        z = (z ^ (z &>> 27)) &* 0x94D049BB133111EB
        z = z ^ (z &>> 31)
        return (z | 0x8000_0000).trailingZeroBitCount &+ 1
    }

    @inline(never)
    private func growLower(_ needed: Int) {
        var newCap = lowerCap
        while newCap < needed {
            newCap &<<= 1
        }
        guard let p = realloc(lowerBase, newCap &<< 3) else {
            fatalError("SkipList lowerBase realloc failed")
        }
        lowerBase = p
        lowerCap = newCap
    }

    @inline(never)
    private func growUpper(_ needed: Int) {
        var newCap = upperCap
        while newCap < needed {
            newCap &<<= 1
        }
        guard let p = realloc(upperBase, newCap &<< 3) else {
            fatalError("SkipList upperBase realloc failed")
        }
        upperBase = p
        upperCap = newCap
    }

    @inline(__always)
    private func allocLower(_ units: Int) -> UInt32 {
        let idx = lowerUsed
        let nextUsed = idx &+ units
        if nextUsed > lowerCap {
            growLower(nextUsed)
        }
        lowerUsed = nextUsed
        return UInt32(truncatingIfNeeded: idx)
    }

    @inline(__always)
    private func allocUpper(_ units: Int) -> UInt32 {
        let idx = upperUsed
        let nextUsed = idx &+ units
        if nextUsed > upperCap {
            growUpper(nextUsed)
        }
        upperUsed = nextUsed
        return UInt32(truncatingIfNeeded: idx) | SkipList.upperFlag
    }

    @inline(__always)
    private func allocNode(_ h: Int) -> UInt32 {
        if h <= 2 {
            let f = free0
            if f != 0 {
                free0 = lowerBase.load(fromByteOffset: Int(f) &<< 3, as: UInt32.self)
                return f
            }
            return allocLower(3)
        }
        if h <= 4 {
            let f = free1
            if f != 0 {
                free1 = lowerBase.load(fromByteOffset: Int(f) &<< 3, as: UInt32.self)
                return f
            }
            return allocLower(4)
        }
        return allocUpperNode(h)
    }

    @inline(never)
    private func allocUpperNode(_ h: Int) -> UInt32 {
        if h <= 6 {
            let f = free2
            if f != 0 {
                free2 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
                return f
            }
            return allocUpper(5)
        }
        if h <= 8 {
            let f = free3
            if f != 0 {
                free3 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
                return f
            }
            return allocUpper(6)
        }
        if h <= 12 {
            let f = free4
            if f != 0 {
                free4 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
                return f
            }
            return allocUpper(8)
        }
        if h <= 16 {
            let f = free5
            if f != 0 {
                free5 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
                return f
            }
            return allocUpper(10)
        }
        if h <= 24 {
            let f = free6
            if f != 0 {
                free6 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
                return f
            }
            return allocUpper(14)
        }
        let f = free7
        if f != 0 {
            free7 = upperBase.load(fromByteOffset: Int(f & SkipList.indexMask) &<< 3, as: UInt32.self)
            return f
        }
        return allocUpper(18)
    }

    @inline(__always)
    private func freeNode(_ idx: UInt32, height h: Int) {
        if h <= 2 {
            lowerBase.storeBytes(of: free0, toByteOffset: Int(idx) &<< 3, as: UInt32.self)
            free0 = idx
            return
        }
        if h <= 4 {
            lowerBase.storeBytes(of: free1, toByteOffset: Int(idx) &<< 3, as: UInt32.self)
            free1 = idx
            return
        }
        freeUpperNode(idx, height: h)
    }

    @inline(never)
    private func freeUpperNode(_ idx: UInt32, height h: Int) {
        let off = Int(idx & SkipList.indexMask) &<< 3
        if h <= 6 {
            upperBase.storeBytes(of: free2, toByteOffset: off, as: UInt32.self)
            free2 = idx
        } else if h <= 8 {
            upperBase.storeBytes(of: free3, toByteOffset: off, as: UInt32.self)
            free3 = idx
        } else if h <= 12 {
            upperBase.storeBytes(of: free4, toByteOffset: off, as: UInt32.self)
            free4 = idx
        } else if h <= 16 {
            upperBase.storeBytes(of: free5, toByteOffset: off, as: UInt32.self)
            free5 = idx
        } else if h <= 24 {
            upperBase.storeBytes(of: free6, toByteOffset: off, as: UInt32.self)
            free6 = idx
        } else {
            upperBase.storeBytes(of: free7, toByteOffset: off, as: UInt32.self)
            free7 = idx
        }
    }

    // MARK: - Public Operations

    func get(_ key: Int64) -> Int64? {
        let hiBase = upperBase
        var currPtr = hiBase
        var stop: UInt32 = 0
        var level = topLevel

        while level >= 4 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let nPtr = hiBase.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    return nPtr.load(as: Int64.self)
                } else {
                    stop = next
                    break
                }
            }
            level &-= 1
        }

        let loBase = lowerBase
        while level >= 0 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let base = Int32(bitPattern: next) < 0 ? hiBase : loBase
                let nPtr = base.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    return nPtr.load(as: Int64.self)
                } else {
                    stop = next
                    break
                }
            }
            level &-= 1
        }
        return nil
    }

    func insert(_ key: Int64, _ value: Int64) -> Bool {
        let hiBase = upperBase
        var curr: UInt32 = SkipList.headerIdx
        var currPtr = hiBase
        var stop: UInt32 = 0
        var level = topLevel

        while level >= 4 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let nPtr = hiBase.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    curr = next
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    nPtr.storeBytes(of: value, as: Int64.self)
                    return false
                } else {
                    stop = next
                    break
                }
            }
            hiBase.storeBytes(of: curr, toByteOffset: SkipList.predByteOffset &+ (level &<< 2), as: UInt32.self)
            level &-= 1
        }

        let loBase = lowerBase
        while level >= 0 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let base = Int32(bitPattern: next) < 0 ? hiBase : loBase
                let nPtr = base.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    curr = next
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    nPtr.storeBytes(of: value, as: Int64.self)
                    return false
                } else {
                    stop = next
                    break
                }
            }
            hiBase.storeBytes(of: curr, toByteOffset: SkipList.predByteOffset &+ (level &<< 2), as: UInt32.self)
            level &-= 1
        }

        let h = randomHeight()
        let newIdx = allocNode(h)
        // Reload bases after allocNode in case realloc moved either buffer.
        let newLoBase = lowerBase
        let newHiBase = upperBase
        let newBase = Int32(bitPattern: newIdx) < 0 ? newHiBase : newLoBase
        let newPtr = newBase.advanced(by: Int(newIdx & SkipList.indexMask) &<< 3)
        newPtr.storeBytes(of: value, as: Int64.self)
        newPtr.storeBytes(of: key, toByteOffset: 8, as: Int64.self)

        let prevHeight = topLevel &+ 1
        let shared = h <= prevHeight ? h : prevHeight
        var L = 0
        while L < shared {
            let off = 16 &+ (L &<< 2)
            let pIdx = newHiBase.load(fromByteOffset: SkipList.predByteOffset &+ (L &<< 2), as: UInt32.self)
            let pBase = Int32(bitPattern: pIdx) < 0 ? newHiBase : newLoBase
            let pPtr = pBase.advanced(by: Int(pIdx & SkipList.indexMask) &<< 3)
            let oldNext = pPtr.load(fromByteOffset: off, as: UInt32.self)
            newPtr.storeBytes(of: oldNext, toByteOffset: off, as: UInt32.self)
            pPtr.storeBytes(of: newIdx, toByteOffset: off, as: UInt32.self)
            L &+= 1
        }
        if h > prevHeight {
            while L < h {
                let off = 16 &+ (L &<< 2)
                newPtr.storeBytes(of: UInt32(0), toByteOffset: off, as: UInt32.self)
                newHiBase.storeBytes(of: newIdx, toByteOffset: off, as: UInt32.self)
                L &+= 1
            }
            topLevel = h &- 1
        }

        count &+= 1
        return true
    }

    @inline(__always)
    private func unlinkFound(
        _ target: UInt32,
        _ tPtr: UnsafeMutableRawPointer,
        _ startCurrPtr: UnsafeMutableRawPointer,
        _ level: Int,
        _ top: Int,
        _ loBase: UnsafeMutableRawPointer,
        _ hiBase: UnsafeMutableRawPointer
    ) {
        let targetHeight = level &+ 1
        var currPtr = startCurrPtr

        let topOff = 16 &+ (level &<< 2)
        let tNext = tPtr.load(fromByteOffset: topOff, as: UInt32.self)
        currPtr.storeBytes(of: tNext, toByteOffset: topOff, as: UInt32.self)

        var L = level &- 1
        while L >= 0 {
            let off = 16 &+ (L &<< 2)
            var nx = currPtr.load(fromByteOffset: off, as: UInt32.self)
            while nx != target {
                let b = Int32(bitPattern: nx) < 0 ? hiBase : loBase
                currPtr = b.advanced(by: Int(nx & SkipList.indexMask) &<< 3)
                nx = currPtr.load(fromByteOffset: off, as: UInt32.self)
            }
            let tn = tPtr.load(fromByteOffset: off, as: UInt32.self)
            currPtr.storeBytes(of: tn, toByteOffset: off, as: UInt32.self)
            L &-= 1
        }

        var newTop = top
        while newTop >= 0 && hiBase.load(fromByteOffset: 16 &+ (newTop &<< 2), as: UInt32.self) == 0 {
            newTop &-= 1
        }
        topLevel = newTop
        count &-= 1
        freeNode(target, height: targetHeight)
    }

    func remove(_ key: Int64) -> Bool {
        let top = topLevel
        if top < 0 { return false }

        let loBase = lowerBase
        let hiBase = upperBase

        // Fast check against the first node (level 0 head):
        // returns immediately for keys < min, and unlinks min in O(1) expected time.
        let first = hiBase.load(fromByteOffset: 16, as: UInt32.self)
        let fBase = Int32(bitPattern: first) < 0 ? hiBase : loBase
        let fPtr = fBase.advanced(by: Int(first & SkipList.indexMask) &<< 3)
        let fk = fPtr.load(fromByteOffset: 8, as: Int64.self)
        if key <= fk {
            if key < fk { return false }
            var L = 0
            while L <= top {
                let off = 16 &+ (L &<< 2)
                if hiBase.load(fromByteOffset: off, as: UInt32.self) != first {
                    break
                }
                let tNext = fPtr.load(fromByteOffset: off, as: UInt32.self)
                hiBase.storeBytes(of: tNext, toByteOffset: off, as: UInt32.self)
                L &+= 1
            }
            var newTop = top
            while newTop >= 0 && hiBase.load(fromByteOffset: 16 &+ (newTop &<< 2), as: UInt32.self) == 0 {
                newTop &-= 1
            }
            topLevel = newTop
            count &-= 1
            freeNode(first, height: L)
            return true
        }

        var currPtr = hiBase
        var stop: UInt32 = 0
        var level = top

        while level >= 4 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let nPtr = hiBase.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    unlinkFound(next, nPtr, currPtr, level, top, loBase, hiBase)
                    return true
                } else {
                    stop = next
                    break
                }
            }
            level &-= 1
        }

        while level >= 0 {
            let linkOff = 16 &+ (level &<< 2)
            var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
            while next != stop {
                let base = Int32(bitPattern: next) < 0 ? hiBase : loBase
                let nPtr = base.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                if nk < key {
                    currPtr = nPtr
                    next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                } else if nk == key {
                    unlinkFound(next, nPtr, currPtr, level, top, loBase, hiBase)
                    return true
                } else {
                    stop = next
                    break
                }
            }
            level &-= 1
        }
        return false
    }

    func range(_ lo: Int64, _ hi: Int64,
               _ outKeys: UnsafeMutablePointer<Int64>,
               _ outVals: UnsafeMutablePointer<Int64>,
               _ limit: Int) -> Int {
        if lo > hi || limit <= 0 || topLevel < 0 { return 0 }

        let loBase = lowerBase
        let hiBase = upperBase
        var currPtr = hiBase
        var stop: UInt32 = 0
        var level = topLevel

        search: do {
            while level >= 4 {
                let linkOff = 16 &+ (level &<< 2)
                var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                while next != stop {
                    let nPtr = hiBase.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                    let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                    if nk < lo {
                        currPtr = nPtr
                        next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                    } else if nk == lo {
                        stop = next
                        break search
                    } else {
                        stop = next
                        break
                    }
                }
                level &-= 1
            }

            while level >= 0 {
                let linkOff = 16 &+ (level &<< 2)
                var next = currPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                while next != stop {
                    let base = Int32(bitPattern: next) < 0 ? hiBase : loBase
                    let nPtr = base.advanced(by: Int(next & SkipList.indexMask) &<< 3)
                    let nk = nPtr.load(fromByteOffset: 8, as: Int64.self)
                    if nk < lo {
                        currPtr = nPtr
                        next = nPtr.load(fromByteOffset: linkOff, as: UInt32.self)
                    } else if nk == lo {
                        stop = next
                        break search
                    } else {
                        stop = next
                        break
                    }
                }
                level &-= 1
            }
        }

        var written = 0
        var idx = stop
        while idx != 0 && written < limit {
            let base = Int32(bitPattern: idx) < 0 ? hiBase : loBase
            let nPtr = base.advanced(by: Int(idx & SkipList.indexMask) &<< 3)
            let k = nPtr.load(fromByteOffset: 8, as: Int64.self)
            if k > hi { break }
            let nextIdx = nPtr.load(fromByteOffset: 16, as: UInt32.self)
            let v = nPtr.load(as: Int64.self)
            outKeys[written] = k
            outVals[written] = v
            written &+= 1
            idx = nextIdx
        }
        return written
    }

    func height() -> Int {
        return topLevel &+ 1
    }

    func levelCount(_ level: Int) -> Int {
        if level < 0 || level > topLevel { return 0 }
        let off = 16 &+ (level &<< 2)
        var c = 0
        var idx = upperBase.load(fromByteOffset: off, as: UInt32.self)
        while idx != 0 {
            c &+= 1
            idx = ptr(idx).load(fromByteOffset: off, as: UInt32.self)
        }
        return c
    }
}
