// Binary min-heap of (i64 key, i64 value) entries.
//
// Layout: one contiguous array of 16-byte entries, 128-byte aligned. Tree
// position p lives at array index p + 1 (1-based), so the children of index j
// are 2j and 2j + 1: a sibling pair always shares one 32-byte block, and the
// 8 great-grandchildren of j (indices 8j .. 8j+7) fill exactly one 128-byte
// cache line. Index 0 holds a sentinel that is <= every entry, so sift-up
// needs no root check.
//
// Each entry is stored as one unsigned 128-bit integer:
//   high 64 bits = key ^ 0x8000..., low 64 bits = value ^ 0x8000...
// Flipping the sign bits maps signed order onto unsigned order, so the
// (key, value) lexicographic order is a single unsigned 128-bit comparison
// (cmp + sbcs on arm64), and loads/stores are single ldp/stp.

#include "heap.h"

#include <stdlib.h>
#include <string.h>

typedef unsigned __int128 ent;

#define SIGN 0x8000000000000000ULL
#define ALIGN 128u
// Heaps at least this large (entries) do not fit in L1; sift-downs then
// prefetch the descendants four levels below the current node.
#define PF_MIN 8192u

struct heap {
    ent *a;       // a[0] = sentinel, a[1..n] = entries
    size_t n;     // number of entries
    size_t cap;   // usable entries: a[1..cap]
    char *raw;    // malloc'd block
    size_t off;   // a == raw + off
};

#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

static inline ent enc(int64_t k, int64_t v) {
    return ((ent)((uint64_t)k ^ SIGN) << 64) | (ent)((uint64_t)v ^ SIGN);
}

static inline void dec(ent e, int64_t *k, int64_t *v) {
    *k = (int64_t)((uint64_t)(e >> 64) ^ SIGN);
    *v = (int64_t)((uint64_t)e ^ SIGN);
}

static inline void prefetch_desc(const ent *a, size_t j, size_t n) {
    // The 16 descendants four levels below j: indices 16j .. 16j+15,
    // two 128-byte lines. Clamped so we never prefetch past the heap.
    size_t i = 16 * j;
    i = i < n ? i : n;
    __builtin_prefetch(a + i, 0, 3);
    __builtin_prefetch(a + i + 8, 0, 3);
}

// ------------------------------------------------------------- allocation

static void set_block(heap *h, char *raw, size_t cap) {
    size_t off = (size_t)(-(uintptr_t)raw) & (ALIGN - 1);
    h->raw = raw;
    h->off = off;
    h->a = (ent *)(void *)(raw + off);
    h->cap = cap;
}

static size_t block_bytes(size_t cap) {
    return (cap + 1) * sizeof(ent) + ALIGN;
}

static heap *alloc_heap(size_t cap) {
    heap *h = malloc(sizeof *h);
    if (!h) abort();
    char *raw = malloc(block_bytes(cap));
    if (!raw) abort();
    set_block(h, raw, cap);
    h->n = 0;
    h->a[0] = 0;  // sentinel: smallest possible encoded entry
    return h;
}

__attribute__((noinline, cold)) static void grow(heap *h) {
    size_t cap = h->cap * 2;
    if (cap < 64) cap = 64;
    size_t old_off = h->off;
    char *raw = realloc(h->raw, block_bytes(cap));
    if (!raw) abort();
    size_t off = (size_t)(-(uintptr_t)raw) & (ALIGN - 1);
    if (off != old_off) memmove(raw + off, raw + old_off, (h->n + 1) * sizeof(ent));
    set_block(h, raw, cap);
}

heap *heap_new(void) { return alloc_heap(64); }

void heap_free(heap *h) {
    if (!h) return;
    free(h->raw);
    free(h);
}

// ---------------------------------------------------------------- sifting

// Bottom-up sift-down (Floyd): the hole at index 1 descends along the path of
// smaller children to a leaf (one comparison per level), then x sifts up from
// there. Heap size is n (a[1..n] valid apart from the hole).
static inline __attribute__((always_inline)) void sift_hole_root(ent *a, size_t n, ent x,
                                                                 bool pf) {
    size_t j = 1, c;
    while ((c = 2 * j) < n) {
        if (pf) prefetch_desc(a, j, n);
        ent l = a[c], r = a[c + 1];
        size_t lt = r < l;
        a[j] = lt ? r : l;
        j = c + lt;
    }
    if (c == n) {
        a[j] = a[c];
        j = c;
    }
    for (;;) {
        size_t p = j >> 1;
        ent pv = a[p];
        if (!(x < pv)) break;
        a[j] = pv;
        j = p;
    }
    a[j] = x;
}

// Top-down sift-down with early exit: x starts at the root.
static inline __attribute__((always_inline)) void sift_down_root(ent *a, size_t n, ent x,
                                                                 bool pf) {
    size_t j = 1, c;
    while ((c = 2 * j) < n) {
        if (pf) prefetch_desc(a, j, n);
        ent l = a[c], r = a[c + 1];
        size_t lt = r < l;
        ent m = lt ? r : l;
        if (!(m < x)) goto done;
        a[j] = m;
        j = c + lt;
    }
    if (c == n && a[c] < x) {
        a[j] = a[c];
        j = c;
    }
done:
    a[j] = x;
}

// Bottom-up sift-down of x into the hole at `root`, used by build. The
// subtrees of root's children are already heaps.
static inline void sift_build(ent *a, size_t n, size_t root, ent x) {
    size_t j = root, c;
    while ((c = 2 * j) < n) {
        ent l = a[c], r = a[c + 1];
        size_t lt = r < l;
        a[j] = lt ? r : l;
        j = c + lt;
    }
    if (c == n) {
        a[j] = a[c];
        j = c;
    }
    while (j > root) {
        size_t p = j >> 1;
        ent pv = a[p];
        if (!(x < pv)) break;
        a[j] = pv;
        j = p;
    }
    a[j] = x;
}

// ------------------------------------------------------------- operations

heap *heap_build(const int64_t *keys, const int64_t *values, size_t count) {
    heap *h = alloc_heap(count < 64 ? 64 : count);
    ent *a = h->a;
    size_t n = count;
    h->n = n;
    size_t half = n / 2;
    for (size_t j = half + 1; j <= n; j++) a[j] = enc(keys[j - 1], values[j - 1]);
    for (size_t j = half; j >= 1; j--) sift_build(a, n, j, enc(keys[j - 1], values[j - 1]));
    return h;
}

void heap_push(heap *h, int64_t key, int64_t value) {
    ent x = enc(key, value);
    size_t n = h->n + 1;
    if (UNLIKELY(n > h->cap)) grow(h);
    ent *a = h->a;
    h->n = n;
    size_t j = n;
    for (;;) {
        size_t p = j >> 1;
        ent pv = a[p];
        if (!(x < pv)) break;
        a[j] = pv;
        j = p;
    }
    a[j] = x;
}

bool heap_peek(const heap *h, int64_t *key, int64_t *value) {
    if (h->n == 0) return false;
    dec(h->a[1], key, value);
    return true;
}

bool heap_pop(heap *h, int64_t *key, int64_t *value) {
    size_t n = h->n;
    if (UNLIKELY(n == 0)) return false;
    ent *a = h->a;
    dec(a[1], key, value);
    ent x = a[n];
    n--;
    h->n = n;
    if (n >= PF_MIN)
        sift_hole_root(a, n, x, true);
    else if (n > 0)
        sift_hole_root(a, n, x, false);
    return true;
}

bool heap_replace(heap *h, int64_t key, int64_t value, int64_t *old_key,
                  int64_t *old_value) {
    size_t n = h->n;
    if (UNLIKELY(n == 0)) {
        heap_push(h, key, value);
        return false;
    }
    ent *a = h->a;
    dec(a[1], old_key, old_value);
    ent x = enc(key, value);
    if (n >= PF_MIN)
        sift_down_root(a, n, x, true);
    else
        sift_down_root(a, n, x, false);
    return true;
}

void heap_push_pop(heap *h, int64_t key, int64_t value, int64_t *out_key,
                   int64_t *out_value) {
    size_t n = h->n;
    ent x = enc(key, value);
    ent *a = h->a;
    if (n == 0 || !(a[1] < x)) {
        *out_key = key;
        *out_value = value;
        return;
    }
    dec(a[1], out_key, out_value);
    if (n >= PF_MIN)
        sift_hole_root(a, n, x, true);
    else
        sift_hole_root(a, n, x, false);
}

size_t heap_len(const heap *h) { return h->n; }

void heap_slot(const heap *h, size_t i, int64_t *key, int64_t *value) {
    dec(h->a[i + 1], key, value);
}
