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

final class DList {
    // 16-byte node: exactly 3 fields (next, prev, value), zero padding.
    // 8 nodes fit per 128-byte Apple M3 cache line with zero cache-line splits.
    // Links and handles are byte offsets into the contiguous node pool (multiples of 16).
    // Offset 0 is the circular sentinel node: sentinel.next is front, sentinel.prev is back.
    // Because 0 means "no node", sentinel links double directly as end-of-list 0s.
    private struct Node {
        var next: UInt32
        var prev: UInt32
        var value: Int64
    }

    private var rawBase: UnsafeMutableRawPointer
    private var usedBytes: UInt32
    private var capBytes: UInt32
    private var freeHead: UInt32
    private var _count: Int

    init() {
        precondition(MemoryLayout<Node>.stride == 16)
        let initialCap = 1024 // 64 nodes * 16 bytes
        guard let p = malloc(initialCap) else {
            fatalError("DList initial allocation failed")
        }
        p.bindMemory(to: Node.self, capacity: initialCap >> 4)
        self.rawBase = p
        self.usedBytes = 16 // offset 0 is the sentinel node
        self.capBytes = UInt32(initialCap)
        self.freeHead = 0
        self._count = 0
        Self.sentinelPtr(p).pointee = Node(next: 0, prev: 0, value: 0)
    }

    deinit {
        free(rawBase)
    }

    @inline(__always)
    private static func sentinelPtr(_ base: UnsafeMutableRawPointer) -> UnsafeMutablePointer<Node> {
        base.assumingMemoryBound(to: Node.self)
    }

    @inline(__always)
    private static func nodePtr(_ base: UnsafeMutableRawPointer, _ offset: UInt32) -> UnsafeMutablePointer<Node> {
        base.advanced(by: Int(offset)).assumingMemoryBound(to: Node.self)
    }

    @inline(__always)
    private static func handlePtr(_ base: UnsafeMutableRawPointer, _ handle: UInt64) -> UnsafeMutablePointer<Node> {
        base.advanced(by: Int(truncatingIfNeeded: handle)).assumingMemoryBound(to: Node.self)
    }

    @inline(never)
    private func grow() {
        let curCap = Int(capBytes)
        let maxCap = 0xFFFF_FFF0 // largest multiple of 16 fitting in UInt32 (~4 GB, 268M nodes)
        if curCap >= maxCap {
            fatalError("DList capacity limit exceeded")
        }
        var newCap = curCap &* 4
        if newCap > maxCap || newCap <= curCap {
            newCap = maxCap
        }
        guard let p = realloc(rawBase, newCap) else {
            fatalError("DList reallocation failed")
        }
        p.bindMemory(to: Node.self, capacity: newCap >> 4)
        rawBase = p
        capBytes = UInt32(truncatingIfNeeded: newCap)
    }

    @inline(__always)
    private func allocNode() -> UInt32 {
        let fh = freeHead
        if fh != 0 {
            freeHead = Self.nodePtr(rawBase, fh).pointee.next
            return fh
        }
        let ub = usedBytes
        if ub == capBytes {
            grow()
        }
        usedBytes = ub &+ 16
        return ub
    }

    @inline(__always)
    var count: Int {
        _count
    }

    @inline(__always)
    func pushFront(_ value: Int64) -> UInt64 {
        let off = allocNode()
        let base = rawBase
        let sentinel = Self.sentinelPtr(base)
        let head = sentinel.pointee.next
        Self.nodePtr(base, off).pointee = Node(next: head, prev: 0, value: value)
        Self.nodePtr(base, head).pointee.prev = off
        sentinel.pointee.next = off
        _count &+= 1
        return UInt64(off)
    }

    @inline(__always)
    func pushBack(_ value: Int64) -> UInt64 {
        let off = allocNode()
        let base = rawBase
        let sentinel = Self.sentinelPtr(base)
        let tail = sentinel.pointee.prev
        Self.nodePtr(base, off).pointee = Node(next: 0, prev: tail, value: value)
        Self.nodePtr(base, tail).pointee.next = off
        sentinel.pointee.prev = off
        _count &+= 1
        return UInt64(off)
    }

    @inline(__always)
    func insertBefore(_ node: UInt64, _ value: Int64) -> UInt64 {
        let off = allocNode()
        let base = rawBase
        let target = UInt32(truncatingIfNeeded: node)
        let tp = Self.nodePtr(base, target)
        let p = tp.pointee.prev
        Self.nodePtr(base, off).pointee = Node(next: target, prev: p, value: value)
        Self.nodePtr(base, p).pointee.next = off
        tp.pointee.prev = off
        _count &+= 1
        return UInt64(off)
    }

    @inline(__always)
    func insertAfter(_ node: UInt64, _ value: Int64) -> UInt64 {
        let off = allocNode()
        let base = rawBase
        let target = UInt32(truncatingIfNeeded: node)
        let tp = Self.nodePtr(base, target)
        let n = tp.pointee.next
        Self.nodePtr(base, off).pointee = Node(next: n, prev: target, value: value)
        tp.pointee.next = off
        Self.nodePtr(base, n).pointee.prev = off
        _count &+= 1
        return UInt64(off)
    }

    @inline(__always)
    func remove(_ node: UInt64) -> Int64 {
        let base = rawBase
        let off = UInt32(truncatingIfNeeded: node)
        let np = Self.nodePtr(base, off)
        let n = np.pointee.next
        let p = np.pointee.prev
        let val = np.pointee.value
        Self.nodePtr(base, p).pointee.next = n
        Self.nodePtr(base, n).pointee.prev = p
        np.pointee.next = freeHead
        freeHead = off
        _count &-= 1
        return val
    }

    @inline(__always)
    func popFront() -> Int64? {
        let base = rawBase
        let sentinel = Self.sentinelPtr(base)
        let head = sentinel.pointee.next
        if head == 0 {
            return nil
        }
        let hp = Self.nodePtr(base, head)
        let n = hp.pointee.next
        let val = hp.pointee.value
        sentinel.pointee.next = n
        Self.nodePtr(base, n).pointee.prev = 0
        hp.pointee.next = freeHead
        freeHead = head
        _count &-= 1
        return val
    }

    @inline(__always)
    func popBack() -> Int64? {
        let base = rawBase
        let sentinel = Self.sentinelPtr(base)
        let tail = sentinel.pointee.prev
        if tail == 0 {
            return nil
        }
        let tp = Self.nodePtr(base, tail)
        let p = tp.pointee.prev
        let val = tp.pointee.value
        sentinel.pointee.prev = p
        Self.nodePtr(base, p).pointee.next = 0
        tp.pointee.next = freeHead
        freeHead = tail
        _count &-= 1
        return val
    }

    @inline(__always)
    func moveToFront(_ node: UInt64) {
        let base = rawBase
        let off = UInt32(truncatingIfNeeded: node)
        let np = Self.nodePtr(base, off)
        let p = np.pointee.prev
        if p == 0 {
            return
        }
        let n = np.pointee.next
        Self.nodePtr(base, p).pointee.next = n
        Self.nodePtr(base, n).pointee.prev = p
        let sentinel = Self.sentinelPtr(base)
        let head = sentinel.pointee.next
        np.pointee.prev = 0
        np.pointee.next = head
        Self.nodePtr(base, head).pointee.prev = off
        sentinel.pointee.next = off
    }

    @inline(__always)
    func front() -> UInt64 {
        UInt64(Self.sentinelPtr(rawBase).pointee.next)
    }

    @inline(__always)
    func back() -> UInt64 {
        UInt64(Self.sentinelPtr(rawBase).pointee.prev)
    }

    @inline(__always)
    func next(_ node: UInt64) -> UInt64 {
        UInt64(Self.handlePtr(rawBase, node).pointee.next)
    }

    @inline(__always)
    func prev(_ node: UInt64) -> UInt64 {
        UInt64(Self.handlePtr(rawBase, node).pointee.prev)
    }

    @inline(__always)
    func get(_ node: UInt64) -> Int64 {
        Self.handlePtr(rawBase, node).pointee.value
    }
}
