#pragma once

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <optional>

struct Entry {
    std::int64_t key;
    std::int64_t value;
};

class Heap {
private:
    using i128 = __int128;
    using u128 = unsigned __int128;

    static constexpr std::uint64_t SIGN_BIT = std::uint64_t(1) << 63;
    static constexpr i128 SENTINEL_MIN = static_cast<i128>(u128(1) << 127);

    // 1-based, 128-byte aligned storage:
    //   data_[0]           = SENTINEL_MIN (stops sift-up without pos > 1 check)
    //   data_[1 .. size_]  = heap entries (spec position i maps to data_[i + 1])
    //   data_[cap_ + 1 ..] = 16-slot tail padding for safe aligned prefetching
    i128* data_;
    std::size_t size_;
    std::size_t cap_;

    [[gnu::always_inline]] static inline i128 pack(std::int64_t key, std::int64_t value) noexcept {
        return static_cast<i128>(
            (static_cast<u128>(static_cast<std::uint64_t>(key)) << 64) |
            (static_cast<std::uint64_t>(value) ^ SIGN_BIT));
    }

    [[gnu::always_inline]] static inline Entry unpack(i128 x) noexcept {
        const auto ux = static_cast<u128>(x);
        const auto key = static_cast<std::int64_t>(static_cast<std::uint64_t>(ux >> 64));
        const auto value = static_cast<std::int64_t>(static_cast<std::uint64_t>(ux) ^ SIGN_BIT);
        return Entry{key, value};
    }

    static inline std::size_t alloc_bytes_for(std::size_t cap) noexcept {
        return (((cap + 16) * sizeof(i128)) + 127) & ~std::size_t(127);
    }

    static inline i128* alloc_aligned(std::size_t cap) noexcept {
        const std::size_t bytes = alloc_bytes_for(cap);
        void* p = std::aligned_alloc(128, bytes);
        if (!p) std::abort();
        return static_cast<i128*>(p);
    }

    [[gnu::noinline]] void grow() {
        const std::size_t new_cap = cap_ == 0 ? 64 : (cap_ << 1);
        const std::size_t bytes = alloc_bytes_for(new_cap);
        i128* next = nullptr;
        if (data_ != nullptr && bytes >= 16384) {
            void* p = std::realloc(data_, bytes);
            if (!p) std::abort();
            if ((reinterpret_cast<std::uintptr_t>(p) & 127) == 0) {
                next = static_cast<i128*>(p);
            } else {
                void* ap = std::aligned_alloc(128, bytes);
                if (!ap) std::abort();
                std::memcpy(ap, p, (size_ + 1) * sizeof(i128));
                std::free(p);
                next = static_cast<i128*>(ap);
            }
        } else {
            next = alloc_aligned(new_cap);
            if (data_ != nullptr) {
                std::memcpy(next, data_, (size_ + 1) * sizeof(i128));
                std::free(data_);
            } else {
                next[0] = SENTINEL_MIN;
            }
        }
        data_ = next;
        cap_ = new_cap;
    }

    [[gnu::always_inline]] static inline std::size_t pull_min_child(i128* __restrict d, std::size_t pos) noexcept {
        const std::size_t c = pos << 1;
        const i128 lc = d[c];
        const i128 rc = d[c + 1];
        const bool r_less = rc < lc;
        d[pos] = r_less ? rc : lc;
        return c + r_less;
    }

    // Sift `item` up from `pos` assuming d[0] == SENTINEL_MIN and ancestors satisfy heap invariant.
    // Performs 1 branchless step first, cutting mispredictions on random/bounce workloads.
    [[gnu::always_inline]] static inline void sift_up_after_bounce(i128* __restrict d, std::size_t pos, i128 item) noexcept {
        const std::size_t p1 = pos >> 1;
        const i128 v1 = d[p1];
        const i128 v2 = d[p1 >> 1];
        const bool lt1 = item < v1;
        d[pos] = lt1 ? v1 : item;
        if (__builtin_expect(!(item < v2), 1)) {
            d[lt1 ? p1 : pos] = item;
            return;
        }
        d[p1] = v2;
        pos = p1 >> 1;
        while (true) {
            const std::size_t parent = pos >> 1;
            const i128 pv = d[parent];
            if (!(item < pv)) break;
            d[pos] = pv;
            pos = parent;
        }
        d[pos] = item;
    }

    // Bottom-up (Floyd) sift-down from root for L1-resident heaps (n <= 4096).
    [[gnu::always_inline]] void sift_down_bottomup_l1(i128 item, std::size_t n) noexcept {
        i128* const __restrict d = data_;
        std::size_t pos = 1;
        const std::size_t last_full = (n - 1) >> 1;
        while (pos <= last_full) {
            pos = pull_min_child(d, pos);
        }
        const std::size_t child = pos << 1;
        if (child == n) {
            d[pos] = d[child];
            pos = child;
        }
        sift_up_after_bounce(d, pos, item);
    }

    // Bottom-up (Floyd) sift-down from root with cache-hierarchy-aware prefetching (n > 4096).
    [[gnu::always_inline]] void sift_down_bottomup_large(i128 item, std::size_t n) noexcept {
        i128* const __restrict d = data_;
        std::size_t pos = 1;
        const std::size_t last_full = (n - 1) >> 1;

        while (pos < 512) {
            pos = pull_min_child(d, pos);
        }
        if (n <= 262144) {
            const std::size_t pf8_end = n >> 3;
            while (pos <= pf8_end) {
                __builtin_prefetch(d + (pos << 3), 0, 3);
                pos = pull_min_child(d, pos);
            }
        } else {
            while (pos < 16384) {
                __builtin_prefetch(d + (pos << 3), 0, 3);
                pos = pull_min_child(d, pos);
            }
            // Level 14 (pos in [16384, 32767]): prefetch level 17 (L2 -> L1)
            __builtin_prefetch(d + (pos << 3), 0, 3);
            const std::size_t pf16_end = n >> 4;
            while (pos <= pf16_end) {
                const std::size_t p16 = pos << 4;
                __builtin_prefetch(d + p16, 0, 3);
                __builtin_prefetch(d + p16 + 8, 0, 3);
                pos = pull_min_child(d, pos);
            }
        }
        while (pos <= last_full) {
            pos = pull_min_child(d, pos);
        }
        const std::size_t child = pos << 1;
        if (child == n) {
            d[pos] = d[child];
            pos = child;
        }
        sift_up_after_bounce(d, pos, item);
    }

    // Top-down sift-down from root for large heaps (n > 4096) in replace() and push_pop().
    // Stops early when item <= min(children) to avoid unnecessary DRAM cache misses,
    // while prefetching 3 levels ahead (all 8 great-grandchildren share one 128B cache line).
    [[gnu::always_inline]] void sift_down_topdown_large(i128 item, std::size_t n) noexcept {
        i128* const __restrict d = data_;
        std::size_t pos = 1;
        const std::size_t last_full = (n - 1) >> 1;

        while (pos < 512) {
            const std::size_t c = pos << 1;
            const i128 lc = d[c];
            const i128 rc = d[c + 1];
            const bool r_less = rc < lc;
            const i128 best_v = r_less ? rc : lc;
            if (!(best_v < item)) {
                d[pos] = item;
                return;
            }
            d[pos] = best_v;
            pos = c + r_less;
        }

        const std::size_t pf8_end = n >> 3;
        while (pos <= pf8_end) {
            __builtin_prefetch(d + (pos << 3), 0, 3);
            const std::size_t c = pos << 1;
            const i128 lc = d[c];
            const i128 rc = d[c + 1];
            const bool r_less = rc < lc;
            const i128 best_v = r_less ? rc : lc;
            if (!(best_v < item)) {
                d[pos] = item;
                return;
            }
            d[pos] = best_v;
            pos = c + r_less;
        }

        while (pos <= last_full) {
            const std::size_t c = pos << 1;
            const i128 lc = d[c];
            const i128 rc = d[c + 1];
            const bool r_less = rc < lc;
            const i128 best_v = r_less ? rc : lc;
            if (!(best_v < item)) {
                d[pos] = item;
                return;
            }
            d[pos] = best_v;
            pos = c + r_less;
        }

        const std::size_t child = pos << 1;
        if (child == n) {
            const i128 lc = d[child];
            if (lc < item) {
                d[pos] = lc;
                pos = child;
            }
        }
        d[pos] = item;
    }

    // Branchless height-1 heapify for nodes in [lo, hi) that each have 2 leaf children.
    [[gnu::always_inline]] static inline void heapify_h1(i128* __restrict d, std::size_t lo, std::size_t hi) noexcept {
        for (std::size_t i = lo; i < hi; ++i) {
            const std::size_t c = i << 1;
            const i128 p = d[i];
            const i128 lc = d[c];
            const i128 rc = d[c + 1];
            const bool r_less = rc < lc;
            const i128 mn = r_less ? rc : lc;
            const bool sw = mn < p;
            d[i] = sw ? mn : p;
            d[c + r_less] = sw ? p : mn;
        }
    }

    // Bottom-up sift-down starting at an arbitrary node `start` during build().
    [[gnu::always_inline]] static inline void sift_down_build(i128* __restrict d, std::size_t start, std::size_t n, std::size_t last_full) noexcept {
        const i128 item = d[start];
        std::size_t pos = start;
        while (pos <= last_full) {
            pos = pull_min_child(d, pos);
        }
        const std::size_t child = pos << 1;
        if (child == n) {
            d[pos] = d[child];
            pos = child;
        }
        while (pos > start) {
            const std::size_t parent = pos >> 1;
            const i128 pv = d[parent];
            if (!(item < pv)) break;
            d[pos] = pv;
            pos = parent;
        }
        d[pos] = item;
    }

public:
    Heap() noexcept : data_(nullptr), size_(0), cap_(0) {}

    Heap(const std::int64_t* keys, const std::int64_t* values, std::size_t count)
        : data_(nullptr), size_(count), cap_(0) {
        if (count == 0) return;

        // Allocate with 25% headroom (+16) so workloads like `mixed` avoid reallocating,
        // while untouched tail virtual pages cost zero physical RAM in `build`.
        cap_ = count + (count >> 2) + 16;
        data_ = alloc_aligned(cap_);
        i128* const __restrict d = data_;
        const std::int64_t* const __restrict ks = keys;
        const std::int64_t* const __restrict vs = values;
        d[0] = SENTINEL_MIN;

        if (count == 1) {
            d[1] = pack(ks[0], vs[0]);
            return;
        }

        const std::size_t last_full = (count - 1) >> 1;

        if (count <= 65536) {
            // Fits inside L2 cache: flat copy + branchless height-1 + bottom-up Floyd heapify.
            for (std::size_t i = 0; i < count; ++i) {
                d[i + 1] = pack(ks[i], vs[i]);
            }
            if ((count & 1) == 0) {
                const std::size_t sc = count >> 1;
                if (d[count] < d[sc]) {
                    const i128 tmp = d[sc];
                    d[sc] = d[count];
                    d[count] = tmp;
                }
            }
            const std::size_t h1_lo = (count >> 2) + 1;
            if (h1_lo <= last_full) {
                heapify_h1(d, h1_lo, last_full + 1);
            }
            for (std::size_t i = count >> 2; i >= 1; --i) {
                sift_down_build(d, i, count, last_full);
            }
            return;
        }

        // Large build (> 65536 entries): L2-cache-tiled subtree build.
        // Partition the tree at power-of-2 root level R so each subtree is <= 65536 entries (~1 MB),
        // fitting completely inside M3's 4 MB L2 cache while copying + heapifying it in one DRAM pass.
        std::size_t R = 1;
        while ((count / R) > 65536) {
            R <<= 1;
        }

        const bool has_single = (count & 1) == 0;
        const std::size_t single_parent = count >> 1;

        for (std::size_t r = R; r < (R << 1); ++r) {
            // Copy all levels of subtree rooted at r into d (stays hot in L2).
            unsigned max_k = 0;
            for (unsigned k = 0;; ++k) {
                const std::size_t lo = r << k;
                if (lo > count) break;
                max_k = k;
                const std::size_t hi = std::min<std::size_t>((r + 1) << k, count + 1);
                for (std::size_t idx = lo; idx < hi; ++idx) {
                    d[idx] = pack(ks[idx - 1], vs[idx - 1]);
                }
            }

            // Level max_k consists solely of leaves.
            // Level max_k - 1 consists of height-1 nodes (and possibly leaves / the single-child node).
            if (max_k >= 1) {
                const std::size_t lo = r << (max_k - 1);
                const std::size_t hi = (r + 1) << (max_k - 1);
                const std::size_t h1_hi = std::min<std::size_t>(hi, last_full + 1);
                if (lo < h1_hi) {
                    heapify_h1(d, lo, h1_hi);
                }
                if (has_single && single_parent >= lo && single_parent < hi) {
                    if (d[count] < d[single_parent]) {
                        const i128 tmp = d[single_parent];
                        d[single_parent] = d[count];
                        d[count] = tmp;
                    }
                }
            }

            // Remaining levels of subtree r, bottom-up from max_k - 2 down to 0.
            for (unsigned k = max_k; k >= 2; --k) {
                const unsigned lvl = k - 2;
                const std::size_t lo = r << lvl;
                const std::size_t hi = (r + 1) << lvl;
                for (std::size_t idx = hi; idx > lo; --idx) {
                    sift_down_build(d, idx - 1, count, last_full);
                }
            }
        }

        // Copy and heapify the top R - 1 ancestors above the subtrees.
        for (std::size_t idx = 1; idx < R; ++idx) {
            d[idx] = pack(ks[idx - 1], vs[idx - 1]);
        }
        for (std::size_t idx = R - 1; idx >= 1; --idx) {
            sift_down_build(d, idx, count, last_full);
        }
    }

    ~Heap() {
        std::free(data_);
    }

    Heap(const Heap&) = delete;
    Heap& operator=(const Heap&) = delete;

    [[gnu::always_inline]] void push(std::int64_t key, std::int64_t value) {
        if (__builtin_expect(size_ == cap_, 0)) {
            grow();
        }
        const i128 item = pack(key, value);
        std::size_t pos = ++size_;
        i128* const __restrict d = data_;

        // 2-level branchless prefix: loads parent, grandparent, and great-grandparent in parallel.
        // Exploits heap invariant d[p3] <= d[p2] <= d[p1] and sentinel d[0] == SENTINEL_MIN.
        const std::size_t p1 = pos >> 1;
        const std::size_t p2 = p1 >> 1;
        const std::size_t p3 = p2 >> 1;
        const i128 v1 = d[p1];
        const i128 v2 = d[p2];
        const i128 v3 = d[p3];
        const bool lt1 = item < v1;
        const bool lt2 = item < v2;
        d[pos] = lt1 ? v1 : item;
        if (__builtin_expect(!(item < v3), 1)) {
            const std::size_t pos1 = lt1 ? p1 : pos;
            d[pos1] = lt2 ? v2 : item;
            d[lt2 ? p2 : pos1] = item;
            return;
        }
        d[p1] = v2;
        d[p2] = v3;
        pos = p3;
        while (true) {
            const std::size_t parent = pos >> 1;
            const i128 pv = d[parent];
            if (!(item < pv)) break;
            d[pos] = pv;
            pos = parent;
        }
        d[pos] = item;
    }

    [[gnu::always_inline]] std::optional<Entry> peek() const noexcept {
        if (__builtin_expect(size_ == 0, 0)) {
            return std::nullopt;
        }
        return unpack(data_[1]);
    }

    [[gnu::always_inline]] std::optional<Entry> pop() noexcept {
        std::size_t n = size_;
        if (__builtin_expect(n == 0, 0)) {
            return std::nullopt;
        }
        i128* const __restrict d = data_;
        const i128 result = d[1];
        const i128 last = d[n];
        --n;
        size_ = n;
        if (__builtin_expect(n == 0, 0)) {
            return unpack(result);
        }
        if (n <= 4096) {
            sift_down_bottomup_l1(last, n);
        } else {
            sift_down_bottomup_large(last, n);
        }
        return unpack(result);
    }

    [[gnu::always_inline]] std::optional<Entry> replace(std::int64_t key, std::int64_t value) {
        const std::size_t n = size_;
        if (__builtin_expect(n == 0, 0)) {
            push(key, value);
            return std::nullopt;
        }
        const i128 result = data_[1];
        const i128 item = pack(key, value);
        if (n <= 4096) {
            sift_down_bottomup_l1(item, n);
        } else {
            sift_down_topdown_large(item, n);
        }
        return unpack(result);
    }

    [[gnu::always_inline]] Entry push_pop(std::int64_t key, std::int64_t value) noexcept {
        const i128 item = pack(key, value);
        const std::size_t n = size_;
        if (__builtin_expect(n == 0, 0)) {
            return Entry{key, value};
        }
        const i128 root = data_[1];
        if (__builtin_expect(!(root < item), 1)) {
            return Entry{key, value};
        }
        if (n <= 4096) {
            sift_down_bottomup_l1(item, n);
        } else {
            sift_down_topdown_large(item, n);
        }
        return unpack(root);
    }

    [[gnu::always_inline]] std::size_t len() const noexcept {
        return size_;
    }

    Entry slot(std::size_t i) const noexcept {
        return unpack(data_[i + 1]);
    }
};
