// Radix tree implementation.
//
// Node layout (one allocation per node, 16-byte header):
//   u32 count        keys in the subtree (this node included)
//   u8  label_len    length of the edge label leading to this node
//   u8  flags        bit0: holds a key, bit1: big node, bits 2..: capacity (small)
//   u8  nchild       number of children (small nodes)
//   u8  sclass       allocation size class (in 16-byte units)
//   i64 value
// small node: keys[cap] (sorted first bytes, padded to 8) | ptrs[cap] | label
// big node:   bitmap[4 x u64] | ptrs[256] (indexed by byte)  | label
// The label is the full edge label (its first byte is also the dispatch byte
// in the parent).

#include "radix.hpp"

#include <cstdlib>
#include <cstring>

namespace {

using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using i64 = std::int64_t;

struct Node {
    u32 count;
    u8 label_len;
    u8 flags;
    u8 nchild;
    u8 sclass;
    i64 value;
};
static_assert(sizeof(Node) == 16);

constexpr u8 F_VAL = 1;
constexpr u8 F_BIG = 2;
constexpr unsigned SMALL_MAX = 16;   // small nodes hold up to 16 children
constexpr unsigned BIG_SHRINK = 12;  // big nodes shrink back at this many
constexpr std::size_t BIG_BODY = 32 + 256 * 8;

inline bool has_val(const Node* n) { return n->flags & F_VAL; }
inline bool is_big(const Node* n) { return n->flags & F_BIG; }
inline unsigned cap_of(const Node* n) { return n->flags >> 2; }
inline std::size_t kpad(unsigned cap) { return (cap + 7) & ~7u; }
inline std::size_t small_body(unsigned cap) { return kpad(cap) + 8 * (std::size_t)cap; }
inline u8* base(const Node* n) { return reinterpret_cast<u8*>(const_cast<Node*>(n)); }
inline u8* skeys(const Node* n) { return base(n) + 16; }
inline Node** sptrs(const Node* n) {
    return reinterpret_cast<Node**>(base(n) + 16 + kpad(cap_of(n)));
}
inline u64* bitmap(const Node* n) { return reinterpret_cast<u64*>(base(n) + 16); }
inline Node** bptrs(const Node* n) { return reinterpret_cast<Node**>(base(n) + 48); }
inline std::size_t body_size(const Node* n) {
    return is_big(n) ? BIG_BODY : small_body(cap_of(n));
}
inline u8* label(const Node* n) { return base(n) + 16 + body_size(n); }

inline u64 ld64(const u8* p) {
    u64 v;
    std::memcpy(&v, p, 8);
    return v;
}
inline u32 ld32(const u8* p) {
    u32 v;
    std::memcpy(&v, p, 4);
    return v;
}
inline u16 ld16(const u8* p) {
    u16 v;
    std::memcpy(&v, p, 2);
    return v;
}

// a[0..n) == b[0..n)
inline bool eq_bytes(const u8* a, const u8* b, std::size_t n) {
    if (n >= 8) {
        std::size_t i = 0;
        for (; i + 8 < n; i += 8)
            if (ld64(a + i) != ld64(b + i)) return false;
        return ld64(a + n - 8) == ld64(b + n - 8);
    }
    if (n >= 4) return ((ld32(a) ^ ld32(b)) | (ld32(a + n - 4) ^ ld32(b + n - 4))) == 0;
    if (n >= 2) return ((ld16(a) ^ ld16(b)) | (ld16(a + n - 2) ^ ld16(b + n - 2))) == 0;
    return n == 0 || a[0] == b[0];
}

// Length of the common prefix of a[0..n) and b[0..n).
inline unsigned mismatch(const u8* a, const u8* b, unsigned n) {
    unsigned i = 0;
    while (i + 8 <= n) {
        u64 d = ld64(a + i) ^ ld64(b + i);
        if (d) return i + ((unsigned)__builtin_ctzll(d) >> 3);
        i += 8;
    }
    while (i < n && a[i] == b[i]) i++;
    return i;
}

constexpr u64 ONES = 0x0101010101010101ULL;
constexpr u64 LOW7 = 0x7F7F7F7F7F7F7F7FULL;
constexpr u64 HIGH = 0x8080808080808080ULL;

// High bit set in exactly the bytes of x that are zero.
inline u64 zero_bytes(u64 x) { return ~(((x & LOW7) + LOW7) | x) & HIGH; }

inline unsigned num_children(const Node* n) {
    if (is_big(n)) {
        const u64* bm = bitmap(n);
        return (unsigned)(__builtin_popcountll(bm[0]) + __builtin_popcountll(bm[1]) +
                          __builtin_popcountll(bm[2]) + __builtin_popcountll(bm[3]));
    }
    return n->nchild;
}

// Slot holding the child for byte b, or nullptr.
inline Node** find_slot(const Node* n, u8 b) {
    if (__builtin_expect(is_big(n), 0)) {
        Node** p = bptrs(n) + b;
        return *p ? p : nullptr;
    }
    unsigned nc = n->nchild;
    if (nc == 0) return nullptr;
    const u8* k = skeys(n);
    u64 pat = ONES * b;
    u64 z = zero_bytes(ld64(k) ^ pat);
    if (nc < 8) z &= (1ULL << (nc * 8)) - 1;
    if (z) return sptrs(n) + ((unsigned)__builtin_ctzll(z) >> 3);
    if (nc > 8) {
        z = zero_bytes(ld64(k + 8) ^ pat);
        if (nc < 16) z &= (1ULL << ((nc - 8) * 8)) - 1;
        if (z) return sptrs(n) + 8 + ((unsigned)__builtin_ctzll(z) >> 3);
    }
    return nullptr;
}

std::size_t collect(const Node* n, i64* out, std::size_t w, std::size_t limit) {
    if (has_val(n)) {
        out[w++] = n->value;
        if (w == limit) return w;
    }
    if (!is_big(n)) {
        unsigned nc = n->nchild;
        Node* const* p = sptrs(n);
        std::size_t rem = limit - w;
        unsigned pf = nc < rem ? nc : (unsigned)rem;
        for (unsigned i = 0; i < pf; i++) __builtin_prefetch(p[i]);
        for (unsigned i = 0; i < nc; i++) {
            const Node* c = p[i];
            if (c->count == 1) {
                out[w++] = c->value;  // a non-root node with one key is a leaf
            } else {
                w = collect(c, out, w, limit);
            }
            if (w == limit) return w;
        }
    } else {
        const u64* bm = bitmap(n);
        Node* const* p = bptrs(n);
        std::size_t rem = limit - w;
        for (unsigned wd = 0; wd < 4 && rem; wd++) {
            u64 bits = bm[wd];
            while (bits && rem) {
                unsigned b = wd * 64 + (unsigned)__builtin_ctzll(bits);
                bits &= bits - 1;
                __builtin_prefetch(p[b]);
                rem--;
            }
        }
        for (unsigned wd = 0; wd < 4; wd++) {
            u64 bits = bm[wd];
            while (bits) {
                unsigned b = wd * 64 + (unsigned)__builtin_ctzll(bits);
                bits &= bits - 1;
                const Node* c = p[b];
                if (c->count == 1) {
                    out[w++] = c->value;
                } else {
                    w = collect(c, out, w, limit);
                }
                if (w == limit) return w;
            }
        }
    }
    return w;
}

std::size_t count_nodes(const Node* n) {
    std::size_t c = 1;
    if (is_big(n)) {
        Node* const* p = bptrs(n);
        for (unsigned b = 0; b < 256; b++)
            if (p[b]) c += count_nodes(p[b]);
    } else {
        Node* const* p = sptrs(n);
        for (unsigned i = 0; i < n->nchild; i++) c += count_nodes(p[i]);
    }
    return c;
}

std::size_t node_height(const Node* n) {
    std::size_t h = 0;
    auto visit = [&](const Node* c) {
        std::size_t x = 1 + node_height(c);
        if (x > h) h = x;
    };
    if (is_big(n)) {
        Node* const* p = bptrs(n);
        for (unsigned b = 0; b < 256; b++)
            if (p[b]) visit(p[b]);
    } else {
        Node* const* p = sptrs(n);
        for (unsigned i = 0; i < n->nchild; i++) visit(p[i]);
    }
    return h;
}

}  // namespace

struct RadixImpl {
    static constexpr std::size_t FIRST_CHUNK = 32 * 1024;
    static constexpr std::size_t MAX_CHUNK = 4 * 1024 * 1024;
    static constexpr std::size_t CHUNK_HDR = 128;

    static void push_free(RadixTree& t, void* p, unsigned cls) {
        *static_cast<void**>(p) = t.free_[cls];
        t.free_[cls] = p;
    }

    static void new_chunk(RadixTree& t) {
        std::size_t tail = (std::size_t)(t.end_ - t.bump_);
        if (tail >= 16) push_free(t, t.bump_, (unsigned)(tail >> 4));
        std::size_t sz = t.next_chunk_;
        if (t.next_chunk_ < MAX_CHUNK) t.next_chunk_ *= 2;
        void* c = std::aligned_alloc(128, sz);
        if (!c) std::abort();
        *static_cast<void**>(c) = t.chunks_;
        t.chunks_ = c;
        t.bump_ = static_cast<unsigned char*>(c) + CHUNK_HDR;
        t.end_ = static_cast<unsigned char*>(c) + sz;
    }

    static void* alloc(RadixTree& t, unsigned cls) {
        void* p = t.free_[cls];
        if (p) {
            t.free_[cls] = *static_cast<void**>(p);
            return p;
        }
        std::size_t bytes = (std::size_t)cls << 4;
        if ((std::size_t)(t.end_ - t.bump_) < bytes) new_chunk(t);
        if (bytes <= 128) {
            // keep small nodes inside one 128-byte cache line
            std::size_t in = (std::size_t)(reinterpret_cast<std::uintptr_t>(t.bump_) & 127);
            if (in + bytes > 128) {
                std::size_t gap = 128 - in;
                if ((std::size_t)(t.end_ - t.bump_) < gap + bytes) {
                    new_chunk(t);
                } else {
                    push_free(t, t.bump_, (unsigned)(gap >> 4));
                    t.bump_ += gap;
                }
            }
        }
        p = t.bump_;
        t.bump_ += bytes;
        return p;
    }

    static void free_node(RadixTree& t, Node* n) { push_free(t, n, n->sclass); }

    static Node* new_node(RadixTree& t, bool big, unsigned cap, unsigned label_len) {
        std::size_t size = 16 + (big ? BIG_BODY : small_body(cap)) + label_len;
        unsigned cls = (unsigned)((size + 15) >> 4);
        Node* n = static_cast<Node*>(alloc(t, cls));
        n->count = 0;
        n->label_len = (u8)label_len;
        n->flags = big ? F_BIG : (u8)(cap << 2);
        n->nchild = 0;
        n->sclass = (u8)cls;
        n->value = 0;
        if (big) std::memset(base(n) + 16, 0, BIG_BODY);
        return n;
    }

    static Node* make_leaf(RadixTree& t, const u8* lab, unsigned len, i64 value) {
        Node* n = new_node(t, false, 0, len);
        n->count = 1;
        n->flags |= F_VAL;
        n->value = value;
        std::memcpy(label(n), lab, len);
        return n;
    }

    // Convert a small node (any nchild <= 16) into a big one.
    static Node* to_big(RadixTree& t, Node* n) {
        Node* g = new_node(t, true, 0, n->label_len);
        g->count = n->count;
        g->flags |= n->flags & F_VAL;
        g->value = n->value;
        std::memcpy(label(g), label(n), n->label_len);
        u64* bm = bitmap(g);
        Node** gp = bptrs(g);
        const u8* k = skeys(n);
        Node** p = sptrs(n);
        for (unsigned i = 0; i < n->nchild; i++) {
            gp[k[i]] = p[i];
            bm[k[i] >> 6] |= 1ULL << (k[i] & 63);
        }
        free_node(t, n);
        return g;
    }

    // Copy of small node n with a new capacity.
    static Node* resize_small(RadixTree& t, Node* n, unsigned cap) {
        Node* g = new_node(t, false, cap, n->label_len);
        g->count = n->count;
        g->flags |= n->flags & F_VAL;
        g->value = n->value;
        g->nchild = n->nchild;
        std::memcpy(label(g), label(n), n->label_len);
        std::memcpy(skeys(g), skeys(n), n->nchild);
        std::memcpy(sptrs(g), sptrs(n), n->nchild * sizeof(Node*));
        free_node(t, n);
        return g;
    }

    // Big node -> small node of capacity 16.
    static Node* to_small(RadixTree& t, Node* n) {
        Node* g = new_node(t, false, SMALL_MAX, n->label_len);
        g->count = n->count;
        g->flags |= n->flags & F_VAL;
        g->value = n->value;
        std::memcpy(label(g), label(n), n->label_len);
        u8* gk = skeys(g);
        Node** gp = sptrs(g);
        const u64* bm = bitmap(n);
        Node** p = bptrs(n);
        unsigned c = 0;
        for (unsigned wd = 0; wd < 4; wd++) {
            u64 bits = bm[wd];
            while (bits) {
                unsigned b = wd * 64 + (unsigned)__builtin_ctzll(bits);
                bits &= bits - 1;
                gk[c] = (u8)b;
                gp[c] = p[b];
                c++;
            }
        }
        g->nchild = (u8)c;
        free_node(t, n);
        return g;
    }

    // Add child c under byte b (absent); returns the (possibly moved) node.
    static Node* add_child(RadixTree& t, Node* n, u8 b, Node* c) {
        if (is_big(n)) {
            bptrs(n)[b] = c;
            bitmap(n)[b >> 6] |= 1ULL << (b & 63);
            return n;
        }
        unsigned nc = n->nchild;
        if (nc == cap_of(n)) {
            if (nc == SMALL_MAX) {
                n = to_big(t, n);
                bptrs(n)[b] = c;
                bitmap(n)[b >> 6] |= 1ULL << (b & 63);
                return n;
            }
            n = resize_small(t, n, nc == 0 ? 2 : nc * 2);
        }
        u8* k = skeys(n);
        Node** p = sptrs(n);
        unsigned i = nc;
        while (i > 0 && k[i - 1] > b) {
            k[i] = k[i - 1];
            p[i] = p[i - 1];
            i--;
        }
        k[i] = b;
        p[i] = c;
        n->nchild = (u8)(nc + 1);
        return n;
    }

    // Remove the child under byte b (present); returns the (possibly moved) node.
    static Node* remove_child(RadixTree& t, Node* n, u8 b) {
        if (is_big(n)) {
            bptrs(n)[b] = nullptr;
            bitmap(n)[b >> 6] &= ~(1ULL << (b & 63));
            if (num_children(n) <= BIG_SHRINK) n = to_small(t, n);
            return n;
        }
        unsigned nc = n->nchild;
        u8* k = skeys(n);
        Node** p = sptrs(n);
        unsigned i = 0;
        while (k[i] != b) i++;
        for (; i + 1 < nc; i++) {
            k[i] = k[i + 1];
            p[i] = p[i + 1];
        }
        n->nchild = (u8)(nc - 1);
        return n;
    }

    // x is a non-root node without a key and with exactly one child:
    // merge it into that child; *slot (which holds x) is updated.
    static void merge(RadixTree& t, Node* x, Node** slot) {
        Node* c = is_big(x) ? nullptr : sptrs(x)[0];
        if (!c) {
            const u64* bm = bitmap(x);
            for (unsigned wd = 0; wd < 4 && !c; wd++)
                if (bm[wd]) c = bptrs(x)[wd * 64 + (unsigned)__builtin_ctzll(bm[wd])];
        }
        unsigned lx = x->label_len, lc = c->label_len;
        unsigned nl = lx + lc;
        std::size_t body = body_size(c);
        std::size_t need = 16 + body + nl;
        if (need <= ((std::size_t)c->sclass << 4)) {
            u8* l = label(c);
            std::memmove(l + lx, l, lc);
            std::memcpy(l, label(x), lx);
            c->label_len = (u8)nl;
            *slot = c;
        } else {
            unsigned cls = (unsigned)((need + 15) >> 4);
            Node* g = static_cast<Node*>(alloc(t, cls));
            std::memcpy(g, c, 16 + body);
            g->sclass = (u8)cls;
            g->label_len = (u8)nl;
            u8* l = label(g);
            std::memcpy(l, label(x), lx);
            std::memcpy(l + lx, label(c), lc);
            free_node(t, c);
            *slot = g;
        }
        free_node(t, x);
    }
};

RadixTree::RadixTree()
    : root_(nullptr), bump_(nullptr), end_(nullptr), chunks_(nullptr),
      next_chunk_(RadixImpl::FIRST_CHUNK) {
    for (int i = 0; i < kClasses; i++) free_[i] = nullptr;
    root_ = RadixImpl::new_node(*this, false, 0, 0);
}

RadixTree::~RadixTree() {
    void* c = chunks_;
    while (c) {
        void* next = *static_cast<void**>(c);
        std::free(c);
        c = next;
    }
}

bool RadixTree::insert(std::span<const std::uint8_t> key, std::int64_t value) {
    const u8* k = key.data();
    const std::size_t len = key.size();
    Node* path[260];
    unsigned depth = 0;
    Node** slot = reinterpret_cast<Node**>(&root_);
    Node* n = *slot;
    std::size_t pos = 0;
    for (;;) {
        if (pos == len) {
            if (has_val(n)) {
                n->value = value;
                return false;
            }
            n->flags |= F_VAL;
            n->value = value;
            n->count++;
            break;
        }
        u8 b = k[pos];
        Node** cs = find_slot(n, b);
        if (!cs) {
            Node* leaf = RadixImpl::make_leaf(*this, k + pos, (unsigned)(len - pos), value);
            n = RadixImpl::add_child(*this, n, b, leaf);
            *slot = n;
            n->count++;
            break;
        }
        Node* c = *cs;
        unsigned L = c->label_len;
        std::size_t rem = len - pos;
        unsigned mx = L < rem ? L : (unsigned)rem;
        u8* cl = label(c);
        unsigned m = 1 + mismatch(cl + 1, k + pos + 1, mx - 1);
        if (m == L) {
            path[depth++] = n;
            slot = cs;
            n = c;
            pos += L;
            continue;
        }
        // split the edge to c after m bytes
        Node* mid = RadixImpl::new_node(*this, false, 2, m);
        std::memcpy(label(mid), cl, m);
        mid->count = c->count + 1;
        u8 cb = cl[m];
        if (pos + m == len) {
            mid->flags |= F_VAL;
            mid->value = value;
            skeys(mid)[0] = cb;
            sptrs(mid)[0] = c;
            mid->nchild = 1;
        } else {
            u8 lb = k[pos + m];
            Node* leaf =
                RadixImpl::make_leaf(*this, k + pos + m, (unsigned)(len - pos - m), value);
            u8* mk = skeys(mid);
            Node** mp = sptrs(mid);
            if (cb < lb) {
                mk[0] = cb; mp[0] = c;
                mk[1] = lb; mp[1] = leaf;
            } else {
                mk[0] = lb; mp[0] = leaf;
                mk[1] = cb; mp[1] = c;
            }
            mid->nchild = 2;
        }
        std::memmove(cl, cl + m, L - m);
        c->label_len = (u8)(L - m);
        *cs = mid;
        n->count++;
        break;
    }
    for (unsigned i = 0; i < depth; i++) path[i]->count++;
    return true;
}

std::optional<std::int64_t> RadixTree::get(std::span<const std::uint8_t> key) const {
    const u8* k = key.data();
    const std::size_t len = key.size();
    const Node* n = static_cast<const Node*>(root_);
    std::size_t pos = 0;
    for (;;) {
        if (pos == len) {
            if (has_val(n)) return n->value;
            return std::nullopt;
        }
        Node** cs = find_slot(n, k[pos]);
        if (!cs) return std::nullopt;
        const Node* c = *cs;
        unsigned L = c->label_len;
        if (L > len - pos) return std::nullopt;
        if (!eq_bytes(label(c) + 1, k + pos + 1, L - 1)) return std::nullopt;
        pos += L;
        n = c;
    }
}

bool RadixTree::remove(std::span<const std::uint8_t> key) {
    const u8* k = key.data();
    const std::size_t len = key.size();
    Node* nodes[260];
    Node** slots[260];
    unsigned depth = 0;
    Node* n = static_cast<Node*>(root_);
    nodes[0] = n;
    slots[0] = reinterpret_cast<Node**>(&root_);
    std::size_t pos = 0;
    while (pos < len) {
        Node** cs = find_slot(n, k[pos]);
        if (!cs) return false;
        Node* c = *cs;
        unsigned L = c->label_len;
        if (L > len - pos) return false;
        if (!eq_bytes(label(c) + 1, k + pos + 1, L - 1)) return false;
        pos += L;
        n = c;
        ++depth;
        nodes[depth] = c;
        slots[depth] = cs;
    }
    if (!has_val(n)) return false;
    n->flags &= (u8)~F_VAL;
    for (unsigned i = 0; i <= depth; i++) nodes[i]->count--;
    if (depth == 0) return true;  // the root stays
    unsigned nc = num_children(n);
    if (nc >= 2) return true;
    if (nc == 1) {
        RadixImpl::merge(*this, n, slots[depth]);
        return true;
    }
    // leaf: unlink it from its parent
    Node* p = nodes[depth - 1];
    u8 b = label(n)[0];
    RadixImpl::free_node(*this, n);
    p = RadixImpl::remove_child(*this, p, b);
    *slots[depth - 1] = p;
    if (depth - 1 == 0) return true;
    if (!has_val(p) && num_children(p) == 1) RadixImpl::merge(*this, p, slots[depth - 1]);
    return true;
}

std::optional<Match> RadixTree::longest_prefix(std::span<const std::uint8_t> key) const {
    const u8* k = key.data();
    const std::size_t len = key.size();
    const Node* n = static_cast<const Node*>(root_);
    std::size_t pos = 0;
    bool found = false;
    std::size_t blen = 0;
    i64 bval = 0;
    for (;;) {
        if (has_val(n)) {
            found = true;
            blen = pos;
            bval = n->value;
        }
        if (pos == len) break;
        Node** cs = find_slot(n, k[pos]);
        if (!cs) break;
        const Node* c = *cs;
        unsigned L = c->label_len;
        if (L > len - pos) break;
        if (!eq_bytes(label(c) + 1, k + pos + 1, L - 1)) break;
        pos += L;
        n = c;
    }
    if (!found) return std::nullopt;
    return Match{blen, bval};
}

// Node whose subtree holds exactly the keys starting with the prefix, or null.
static inline const Node* locate(const Node* n, const u8* k, std::size_t len) {
    std::size_t pos = 0;
    for (;;) {
        if (pos == len) return n;
        Node** cs = find_slot(n, k[pos]);
        if (!cs) return nullptr;
        const Node* c = *cs;
        unsigned L = c->label_len;
        std::size_t rem = len - pos;
        if (L >= rem) return eq_bytes(label(c) + 1, k + pos + 1, rem - 1) ? c : nullptr;
        if (!eq_bytes(label(c) + 1, k + pos + 1, L - 1)) return nullptr;
        pos += L;
        n = c;
    }
}

std::size_t RadixTree::prefix_count(std::span<const std::uint8_t> prefix) const {
    const Node* n = locate(static_cast<const Node*>(root_), prefix.data(), prefix.size());
    return n ? n->count : 0;
}

std::size_t RadixTree::prefix_values(std::span<const std::uint8_t> prefix,
                                     std::int64_t* out_values, std::size_t limit) const {
    if (limit == 0) return 0;
    const Node* n = locate(static_cast<const Node*>(root_), prefix.data(), prefix.size());
    if (!n || n->count == 0) return 0;
    return collect(n, out_values, 0, limit);
}

std::size_t RadixTree::len() const { return static_cast<const Node*>(root_)->count; }

std::size_t RadixTree::node_count() const {
    return count_nodes(static_cast<const Node*>(root_));
}

std::size_t RadixTree::height() const { return node_height(static_cast<const Node*>(root_)); }
