#include "heap.h"

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

__extension__ typedef unsigned __int128 u128;

#define SIGN_BIT        ((uint64_t)1ULL << 63)
#define INITIAL_CAP     16u
#define PREFETCH_SLACK  16u
#define CACHE_LINE      128u
#define SMALL_THRESHOLD 4096u
#define BUILD_SUBTREE   65536u

struct heap {
    u128  *a;    /* 128-byte aligned; a[0] = 0 sentinel; a[1..size] = entries */
    size_t size;
    size_t cap;  /* max entries before growth */
    void  *raw;  /* original malloc/realloc pointer */
};

static inline u128 pack_entry(int64_t key, int64_t value) {
    uint64_t uk = (uint64_t)key ^ SIGN_BIT;
    uint64_t uv = (uint64_t)value ^ SIGN_BIT;
    return ((u128)uk << 64) | (u128)uv;
}

static inline void unpack_entry(u128 e, int64_t *key, int64_t *value) {
    *key = (int64_t)((uint64_t)(e >> 64) ^ SIGN_BIT);
    *value = (int64_t)((uint64_t)e ^ SIGN_BIT);
}

static size_t buf_bytes(size_t cap) {
    const size_t max_elems = (SIZE_MAX - CACHE_LINE) / sizeof(u128);
    if (cap > max_elems - 1u - PREFETCH_SLACK) {
        abort();
    }
    return (cap + 1u + PREFETCH_SLACK) * sizeof(u128) + CACHE_LINE;
}

static u128 *align_ptr(void *raw) {
    uintptr_t p = ((uintptr_t)raw + (CACHE_LINE - 1u)) & ~(uintptr_t)(CACHE_LINE - 1u);
    return (u128 *)p;
}

static __attribute__((noinline)) void heap_grow(heap *h) {
    size_t new_cap = h->cap <= SIZE_MAX / 2u ? h->cap * 2u : SIZE_MAX;
    size_t new_bytes = buf_bytes(new_cap);
    size_t old_off = (size_t)((uintptr_t)h->a - (uintptr_t)h->raw);

    void *new_raw = realloc(h->raw, new_bytes);
    if (!new_raw) {
        abort();
    }
    u128 *new_a = align_ptr(new_raw);
    size_t new_off = (size_t)((uintptr_t)new_a - (uintptr_t)new_raw);
    if (__builtin_expect(new_off != old_off, 0)) {
        memmove(new_a, (const char *)new_raw + old_off, (h->size + 1u) * sizeof(u128));
    }
    h->raw = new_raw;
    h->a = new_a;
    h->cap = new_cap;
}

/* Bottom-up (Floyd) sift-down for L1-resident heaps (n <= SMALL_THRESHOLD). */
static inline void sift_down_bu_small(u128 *restrict a, size_t n, u128 x) {
    size_t idx = 1;
    size_t c = 2;
    while (c < n) {
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        c += (size_t)r_lt_l;
        a[idx] = r_lt_l ? right : left;
        idx = c;
        c = idx << 1;
    }
    if (c == n) {
        a[idx] = a[c];
        idx = c;
    }
    size_t parent = idx >> 1;
    u128 p = a[parent];
    while (x < p) {
        a[idx] = p;
        idx = parent;
        parent = idx >> 1;
        p = a[parent];
    }
    a[idx] = x;
}

/* Bottom-up (Floyd) sift-down with 4-level prefetching for large heaps. */
static __attribute__((noinline)) void sift_down_bu_large(u128 *restrict a, size_t n, u128 x) {
    size_t idx = 1;
    size_t c = 2;
    size_t pf_limit = n >> 3;
    while (c <= pf_limit) {
        size_t pf = c << 3;
        __builtin_prefetch(&a[pf], 0, 3);
        __builtin_prefetch(&a[pf + 8], 0, 3);
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        c += (size_t)r_lt_l;
        a[idx] = r_lt_l ? right : left;
        idx = c;
        c = idx << 1;
    }
    while (c < n) {
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        c += (size_t)r_lt_l;
        a[idx] = r_lt_l ? right : left;
        idx = c;
        c = idx << 1;
    }
    if (c == n) {
        a[idx] = a[c];
        idx = c;
    }
    size_t parent = idx >> 1;
    u128 p = a[parent];
    while (x < p) {
        a[idx] = p;
        idx = parent;
        parent = idx >> 1;
        p = a[parent];
    }
    a[idx] = x;
}

static __attribute__((noinline)) void sift_down_bu_dispatch(u128 *restrict a, size_t n, u128 x) {
    if (n <= SMALL_THRESHOLD) {
        sift_down_bu_small(a, n, x);
    } else {
        sift_down_bu_large(a, n, x);
    }
}

/* Top-down sift-down with 4-level prefetching for large-heap replace(). */
static __attribute__((noinline)) void sift_down_td_large(u128 *restrict a, size_t n, u128 x) {
    size_t idx = 1;
    size_t c = 2;
    size_t pf_limit = n >> 3;
    while (c <= pf_limit) {
        size_t pf = c << 3;
        __builtin_prefetch(&a[pf], 0, 3);
        __builtin_prefetch(&a[pf + 8], 0, 3);
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        u128 child = r_lt_l ? right : left;
        if (!(child < x)) {
            a[idx] = x;
            return;
        }
        c += (size_t)r_lt_l;
        a[idx] = child;
        idx = c;
        c = idx << 1;
    }
    while (c < n) {
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        u128 child = r_lt_l ? right : left;
        if (!(child < x)) {
            a[idx] = x;
            return;
        }
        c += (size_t)r_lt_l;
        a[idx] = child;
        idx = c;
        c = idx << 1;
    }
    if (c == n) {
        u128 left = a[c];
        if (left < x) {
            a[idx] = left;
            idx = c;
        }
    }
    a[idx] = x;
}

/* Top-down sift-down from an arbitrary node, used in O(m) heap_build(). */
static inline void sift_down_build(u128 *restrict a, size_t n, size_t idx) {
    u128 x = a[idx];
    size_t c = idx << 1;
    while (c < n) {
        u128 left = a[c];
        u128 right = a[c + 1];
        bool r_lt_l = right < left;
        u128 child = r_lt_l ? right : left;
        if (!(child < x)) {
            a[idx] = x;
            return;
        }
        c += (size_t)r_lt_l;
        a[idx] = child;
        idx = c;
        c = idx << 1;
    }
    if (c == n) {
        u128 left = a[c];
        if (left < x) {
            a[idx] = left;
            idx = c;
        }
    }
    a[idx] = x;
}

/* Branchless 1-level sift-down for nodes whose two children are both leaves. */
static inline void heapify_leaf_parent(u128 *restrict a, size_t i) {
    size_t c = i << 1;
    u128 left = a[c];
    u128 right = a[c + 1];
    u128 x = a[i];
    bool r_lt_l = right < left;
    u128 mc = r_lt_l ? right : left;
    bool do_swap = mc < x;
    a[i] = do_swap ? mc : x;
    a[c + (size_t)r_lt_l] = do_swap ? x : mc;
}

heap *heap_new(void) {
    heap *h = (heap *)malloc(sizeof(heap));
    if (!h) {
        abort();
    }
    void *raw = malloc(buf_bytes(INITIAL_CAP));
    if (!raw) {
        abort();
    }
    u128 *a = align_ptr(raw);
    a[0] = (u128)0;
    h->a = a;
    h->size = 0;
    h->cap = INITIAL_CAP;
    h->raw = raw;
    return h;
}

heap *heap_build(const int64_t *keys, const int64_t *values, size_t count) {
    heap *h = (heap *)malloc(sizeof(heap));
    if (!h) {
        abort();
    }
    size_t cap = count < INITIAL_CAP ? INITIAL_CAP : count;
    void *raw = malloc(buf_bytes(cap));
    if (!raw) {
        abort();
    }
    u128 *restrict a = align_ptr(raw);
    a[0] = (u128)0;
    h->a = a;
    h->size = count;
    h->cap = cap;
    h->raw = raw;

    if (count == 0) {
        return h;
    }

    size_t half = count >> 1;
    size_t quarter = count >> 2;

    if (count <= BUILD_SUBTREE) {
        for (size_t i = 0; i < count; i++) {
            a[i + 1] = pack_entry(keys[i], values[i]);
        }
        if (count >= 2) {
            size_t i = half;
            if ((count & 1u) == 0) {
                u128 x = a[i];
                u128 left = a[count];
                if (left < x) {
                    a[i] = left;
                    a[count] = x;
                }
                i--;
            }
            while (i > quarter) {
                heapify_leaf_parent(a, i);
                i--;
            }
            while (i >= 1) {
                sift_down_build(a, count, i);
                i--;
            }
        }
        return h;
    }

    /* Cache-blocked Floyd build: copy and heapify one L2-resident subtree at a time. */
    size_t subtrees = 1;
    while ((count / subtrees) > BUILD_SUBTREE) {
        subtrees <<= 1;
    }

    for (size_t r = subtrees; r < (subtrees << 1); r++) {
        size_t max_d = 0;
        for (size_t d = 0;; d++) {
            size_t lo = r << d;
            if (lo > count) {
                break;
            }
            size_t hi = ((r + 1u) << d) - 1u;
            if (hi > count) {
                hi = count;
            }
            for (size_t idx = lo; idx <= hi; idx++) {
                a[idx] = pack_entry(keys[idx - 1u], values[idx - 1u]);
            }
            max_d = d;
        }

        for (size_t d = max_d; d-- > 0;) {
            size_t lo = r << d;
            if (lo > half) {
                continue;
            }
            size_t hi = ((r + 1u) << d) - 1u;
            if (hi > half) {
                hi = half;
            }
            size_t i = hi;
            if (i == half && (count & 1u) == 0) {
                u128 x = a[i];
                u128 left = a[count];
                if (left < x) {
                    a[i] = left;
                    a[count] = x;
                }
                i--;
            }
            size_t leaf_lo = lo > quarter ? lo : (quarter + 1u);
            while (i >= leaf_lo) {
                heapify_leaf_parent(a, i);
                i--;
            }
            while (i >= lo) {
                sift_down_build(a, count, i);
                i--;
            }
        }
    }

    for (size_t idx = 1; idx < subtrees; idx++) {
        a[idx] = pack_entry(keys[idx - 1u], values[idx - 1u]);
    }
    for (size_t i = subtrees - 1u; i >= 1; i--) {
        sift_down_build(a, count, i);
    }

    return h;
}

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

void heap_push(heap *h, int64_t key, int64_t value) {
    if (__builtin_expect(h->size == h->cap, 0)) {
        heap_grow(h);
    }
    u128 x = pack_entry(key, value);
    size_t idx = ++h->size;
    u128 *restrict a = h->a;
    size_t parent = idx >> 1;
    u128 p = a[parent];
    if (x < p) {
        do {
            a[idx] = p;
            idx = parent;
            parent = idx >> 1;
            p = a[parent];
        } while (x < p);
    }
    a[idx] = x;
}

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

bool heap_pop(heap *h, int64_t *key, int64_t *value) {
    size_t n = h->size;
    if (__builtin_expect(n == 0, 0)) {
        return false;
    }
    u128 *restrict a = h->a;
    unpack_entry(a[1], key, value);
    n--;
    h->size = n;
    if (__builtin_expect(n == 0, 0)) {
        return true;
    }
    u128 x = a[n + 1u];
    if (n <= SMALL_THRESHOLD) {
        sift_down_bu_small(a, n, x);
    } else {
        sift_down_bu_large(a, n, x);
    }
    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->size;
    u128 x = pack_entry(key, value);
    if (__builtin_expect(n == 0, 0)) {
        h->a[1] = x;
        h->size = 1;
        return false;
    }
    u128 *restrict a = h->a;
    unpack_entry(a[1], old_key, old_value);
    if (n <= SMALL_THRESHOLD) {
        sift_down_bu_small(a, n, x);
    } else {
        sift_down_td_large(a, n, x);
    }
    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->size;
    if (__builtin_expect(n == 0, 0)) {
        *out_key = key;
        *out_value = value;
        return;
    }
    u128 *restrict a = h->a;
    u128 root = a[1];
    u128 x = pack_entry(key, value);
    if (x <= root) {
        *out_key = key;
        *out_value = value;
        return;
    }
    unpack_entry(root, out_key, out_value);
    sift_down_bu_dispatch(a, n, x);
}

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

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