//! Radix tree (path-compressed byte trie) with subtree counts.
//!
//! Every node is one variable-sized block from a size-class pool:
//!
//!   [ header (20 bytes) | label space | child first-bytes (cap) | pad | child ptrs (cap) ]
//!
//! The label lives inside the node at `lab_off` within `lab_space` bytes, so an
//! edge split trims the lower node's label in place (lab_off += c) and a merge
//! can often prepend the parent's label in place again. Child first-bytes are
//! kept sorted (key order for traversal) and searched with a 16-byte vector
//! compare.

const std = @import("std");

pub const Match = struct { length: usize, value: i64 };

const HDR: usize = 20;
const MAX_BLOCK: usize = 2608; // > HDR + 255 + 256 + 7 + 256 * 8
const NCLASS: usize = MAX_BLOCK / 16 + 1;

const Node = extern struct {
    value: i64,
    count: u32,
    nchild: u16,
    cap: u16,
    lab_len: u8,
    lab_off: u8,
    lab_space: u8,
    has_value: u8,
    // NOTE: @sizeOf(Node) is 24 because of alignment, but data starts at HDR
    // (20). Never assign a whole Node by value.

    inline fn base(n: *Node) [*]u8 {
        return @ptrCast(n);
    }
    inline fn label(n: *Node) [*]u8 {
        return n.base() + HDR + n.lab_off;
    }
    inline fn keys(n: *Node) [*]u8 {
        return n.base() + HDR + n.lab_space;
    }
    inline fn ptrs(n: *Node) [*]*Node {
        const off = (HDR + @as(usize, n.lab_space) + n.cap + 7) & ~@as(usize, 7);
        return @ptrCast(@alignCast(n.base() + off));
    }
};

inline fn blockSize(lab_space: usize, cap: usize) usize {
    const raw = if (cap == 0) HDR + lab_space else ((HDR + lab_space + cap + 7) & ~@as(usize, 7)) + cap * 8;
    return (raw + 15) & ~@as(usize, 15);
}

inline fn nodeSize(n: *Node) usize {
    return blockSize(n.lab_space, n.cap);
}

inline fn rd64(p: [*]const u8) u64 {
    return @as(*align(1) const u64, @ptrCast(p)).*;
}

inline fn eqBytes(a: [*]const u8, b: [*]const u8, n: usize) bool {
    var i: usize = 0;
    while (i + 8 <= n) : (i += 8) {
        if (rd64(a + i) != rd64(b + i)) return false;
    }
    while (i < n) : (i += 1) {
        if (a[i] != b[i]) return false;
    }
    return true;
}

const V16 = @Vector(16, u8);

/// Index of the child whose label starts with `b`, or null.
inline fn findChild(n: *Node, b: u8) ?usize {
    const nc: usize = n.nchild;
    const ks = n.keys();
    const needle: V16 = @splat(b);
    var i: usize = 0;
    while (i < nc) : (i += 16) {
        // Reading 16 bytes is safe: when cap >= 2 the pointer array follows.
        const v: V16 = ks[i..][0..16].*;
        var m: u32 = @as(u16, @bitCast(v == needle));
        const remain = nc - i;
        if (remain < 16) m &= (@as(u32, 1) << @intCast(remain)) - 1;
        if (m != 0) return i + @ctz(m);
    }
    return null;
}

/// Number of child first-bytes smaller than `b`.
inline fn lowerBound(n: *Node, b: u8) usize {
    const nc: usize = n.nchild;
    const ks = n.keys();
    const needle: V16 = @splat(b);
    var i: usize = 0;
    var cnt: usize = 0;
    while (i < nc) : (i += 16) {
        const v: V16 = ks[i..][0..16].*;
        var m: u32 = @as(u16, @bitCast(v < needle));
        const remain = nc - i;
        if (remain < 16) m &= (@as(u32, 1) << @intCast(remain)) - 1;
        cnt += @popCount(m);
    }
    return cnt;
}

const FreeBlock = struct { next: ?*FreeBlock };
const Chunk = struct { next: ?*Chunk, len: usize };

const Pool = struct {
    allocator: std.mem.Allocator,
    free: [NCLASS]?*FreeBlock = @splat(null),
    cur: usize = 0,
    end: usize = 0,
    chunks: ?*Chunk = null,
    next_chunk: usize = 64 * 1024,

    fn alloc(self: *Pool, size: usize) std.mem.Allocator.Error!*Node {
        const cls = size >> 4;
        if (self.free[cls]) |b| {
            self.free[cls] = b.next;
            return @ptrCast(@alignCast(b));
        }
        if (self.end - self.cur < size) {
            @branchHint(.unlikely);
            try self.newChunk(size);
        }
        const p = self.cur;
        self.cur += size;
        return @ptrFromInt(p);
    }

    inline fn release(self: *Pool, n: *Node, size: usize) void {
        const cls = size >> 4;
        const b: *FreeBlock = @ptrCast(@alignCast(n));
        b.next = self.free[cls];
        self.free[cls] = b;
    }

    fn newChunk(self: *Pool, need: usize) std.mem.Allocator.Error!void {
        const sz = @max(self.next_chunk, need + 16);
        const mem = try self.allocator.alignedAlloc(u8, .@"16", sz);
        if (self.next_chunk < 8 * 1024 * 1024) self.next_chunk *= 2;
        // Recycle the tail of the old chunk.
        const left = self.end - self.cur;
        if (left >= 16) {
            const b: *FreeBlock = @ptrFromInt(self.cur);
            const cls = left >> 4;
            b.next = self.free[cls];
            self.free[cls] = b;
        }
        const ch: *Chunk = @ptrCast(mem.ptr);
        ch.* = .{ .next = self.chunks, .len = sz };
        self.chunks = ch;
        self.cur = @intFromPtr(mem.ptr) + 16;
        self.end = @intFromPtr(mem.ptr) + sz;
    }

    fn deinit(self: *Pool) void {
        var c = self.chunks;
        while (c) |ch| {
            c = ch.next;
            const p: [*]align(16) u8 = @ptrCast(@alignCast(ch));
            self.allocator.free(p[0..ch.len]);
        }
        self.chunks = null;
    }
};

const MAX_DEPTH = 257;

pub const RadixTree = struct {
    root: ?*Node,
    n: usize,
    pool: Pool,

    pub fn init(allocator: std.mem.Allocator) RadixTree {
        return .{ .root = null, .n = 0, .pool = .{ .allocator = allocator } };
    }

    pub fn deinit(self: *RadixTree) void {
        self.pool.deinit();
        self.root = null;
        self.n = 0;
    }

    fn newNode(self: *RadixTree, lab: []const u8, cap: usize) std.mem.Allocator.Error!*Node {
        const nd = try self.pool.alloc(blockSize(lab.len, cap));
        nd.value = 0;
        nd.count = 0;
        nd.nchild = 0;
        nd.cap = @intCast(cap);
        nd.lab_len = @intCast(lab.len);
        nd.lab_off = 0;
        nd.lab_space = @intCast(lab.len);
        nd.has_value = 0;
        if (lab.len > 0) @memcpy(nd.label()[0..lab.len], lab);
        return nd;
    }

    /// Copy of `old` with label `prefix ++ old.label` and capacity `cap`.
    fn copyNode(self: *RadixTree, old: *Node, prefix: []const u8, cap: usize) std.mem.Allocator.Error!*Node {
        const ll: usize = prefix.len + old.lab_len;
        const nd = try self.pool.alloc(blockSize(ll, cap));
        nd.value = old.value;
        nd.count = old.count;
        nd.nchild = old.nchild;
        nd.cap = @intCast(cap);
        nd.lab_len = @intCast(ll);
        nd.lab_off = 0;
        nd.lab_space = @intCast(ll);
        nd.has_value = old.has_value;
        const lab = nd.label();
        if (prefix.len > 0) @memcpy(lab[0..prefix.len], prefix);
        if (old.lab_len > 0) @memcpy(lab[prefix.len..ll], old.label()[0..old.lab_len]);
        const nc: usize = old.nchild;
        if (nc > 0) {
            @memcpy(nd.keys()[0..nc], old.keys()[0..nc]);
            @memcpy(nd.ptrs()[0..nc], old.ptrs()[0..nc]);
        }
        return nd;
    }

    inline fn freeNode(self: *RadixTree, nd: *Node) void {
        self.pool.release(nd, nodeSize(nd));
    }

    pub fn insert(self: *RadixTree, key: []const u8, value: i64) std.mem.Allocator.Error!bool {
        if (self.root == null) self.root = try self.newNode("", 0);
        var stack: [MAX_DEPTH]*Node = undefined;
        var sp: usize = 0;
        var slot: **Node = @ptrCast(&self.root);
        var node = slot.*;
        var pos: usize = 0;
        const kp = key.ptr;
        while (true) {
            const L: usize = node.lab_len;
            const lab = node.label();
            const rem = key.len - pos;
            const lim = @min(L, rem);
            var c: usize = @min(L, 1); // first byte already matched (non-root)
            while (c < lim and lab[c] == kp[pos + c]) c += 1;
            if (c < L) {
                // Split the edge into `node` after c bytes.
                const key_ends = pos + c == key.len;
                const mid = try self.newNode(lab[0..c], 2);
                var leaf: *Node = undefined;
                if (!key_ends) {
                    leaf = self.newNode(key[pos + c ..], 0) catch |e| {
                        self.freeNode(mid);
                        return e;
                    };
                    leaf.value = value;
                    leaf.has_value = 1;
                    leaf.count = 1;
                }
                node.lab_off += @intCast(c);
                node.lab_len -= @intCast(c);
                mid.count = node.count + 1;
                const nb = node.label()[0];
                const mk = mid.keys();
                const mp = mid.ptrs();
                if (key_ends) {
                    mid.value = value;
                    mid.has_value = 1;
                    mid.nchild = 1;
                    mk[0] = nb;
                    mp[0] = node;
                } else {
                    mid.nchild = 2;
                    const lb = kp[pos + c];
                    if (lb < nb) {
                        mk[0] = lb;
                        mp[0] = leaf;
                        mk[1] = nb;
                        mp[1] = node;
                    } else {
                        mk[0] = nb;
                        mp[0] = node;
                        mk[1] = lb;
                        mp[1] = leaf;
                    }
                }
                slot.* = mid;
                for (stack[0..sp]) |a| a.count += 1;
                self.n += 1;
                return true;
            }
            pos += L;
            if (pos == key.len) {
                if (node.has_value != 0) {
                    node.value = value;
                    return false;
                }
                node.value = value;
                node.has_value = 1;
                node.count += 1;
                for (stack[0..sp]) |a| a.count += 1;
                self.n += 1;
                return true;
            }
            const b = kp[pos];
            if (findChild(node, b)) |idx| {
                stack[sp] = node;
                sp += 1;
                slot = &node.ptrs()[idx];
                node = slot.*;
                continue;
            }
            // Add a new leaf child.
            const leaf = try self.newNode(key[pos..], 0);
            leaf.value = value;
            leaf.has_value = 1;
            leaf.count = 1;
            if (node.nchild == node.cap) {
                const newcap: usize = if (node.cap == 0) 2 else @as(usize, node.cap) * 2;
                const grown = self.copyNode(node, "", newcap) catch |e| {
                    self.freeNode(leaf);
                    return e;
                };
                slot.* = grown;
                self.freeNode(node);
                node = grown;
            }
            const nc: usize = node.nchild;
            const idx = lowerBound(node, b);
            const ks = node.keys();
            const ps = node.ptrs();
            if (idx < nc) {
                @memmove(ks[idx + 1 .. nc + 1], ks[idx..nc]);
                @memmove(ps[idx + 1 .. nc + 1], ps[idx..nc]);
            }
            ks[idx] = b;
            ps[idx] = leaf;
            node.nchild += 1;
            node.count += 1;
            for (stack[0..sp]) |a| a.count += 1;
            self.n += 1;
            return true;
        }
    }

    pub fn get(self: *const RadixTree, key: []const u8) ?i64 {
        var node = self.root orelse return null;
        var pos: usize = 0;
        const kp = key.ptr;
        while (true) {
            const L: usize = node.lab_len;
            if (key.len - pos < L) return null;
            if (L > 1 and !eqBytes(node.label() + 1, kp + pos + 1, L - 1)) return null;
            pos += L;
            if (pos == key.len) {
                return if (node.has_value != 0) node.value else null;
            }
            const idx = findChild(node, kp[pos]) orelse return null;
            node = node.ptrs()[idx];
        }
    }

    /// Merge `p` (no value, one child `c`) into `c`; returns the node that
    /// replaces `p` in its parent. The caller frees `p`.
    fn mergeChild(self: *RadixTree, p: *Node, c: *Node) std.mem.Allocator.Error!*Node {
        const pl: usize = p.lab_len;
        if (c.lab_off >= pl) {
            c.lab_off -= @intCast(pl);
            c.lab_len += @intCast(pl);
            @memcpy(c.label()[0..pl], p.label()[0..pl]);
            return c;
        }
        const nd = try self.copyNode(c, p.label()[0..pl], c.cap);
        self.freeNode(c);
        return nd;
    }

    pub fn remove(self: *RadixTree, key: []const u8) std.mem.Allocator.Error!bool {
        var node = self.root orelse return false;
        var stack: [MAX_DEPTH]*Node = undefined;
        var idxs: [MAX_DEPTH]usize = undefined;
        var sp: usize = 0;
        var pos: usize = 0;
        const kp = key.ptr;
        while (true) {
            const L: usize = node.lab_len;
            if (key.len - pos < L) return false;
            if (L > 1 and !eqBytes(node.label() + 1, kp + pos + 1, L - 1)) return false;
            pos += L;
            if (pos == key.len) break;
            const idx = findChild(node, kp[pos]) orelse return false;
            stack[sp] = node;
            idxs[sp] = idx;
            sp += 1;
            node = node.ptrs()[idx];
        }
        if (node.has_value == 0) return false;

        if (sp == 0 or node.nchild >= 2) {
            node.has_value = 0;
            node.count -= 1;
            for (stack[0..sp]) |a| a.count -= 1;
            self.n -= 1;
            return true;
        }
        const parent = stack[sp - 1];
        const pidx = idxs[sp - 1];
        if (node.nchild == 1) {
            // Node keeps no key and one child: merge it into the child.
            const merged = try self.mergeChild(node, node.ptrs()[0]);
            parent.ptrs()[pidx] = merged;
            self.freeNode(node);
            for (stack[0..sp]) |a| a.count -= 1;
            self.n -= 1;
            return true;
        }
        // Leaf: unlink it from the parent.
        if (sp >= 2 and parent.has_value == 0 and parent.nchild == 2) {
            // Parent is left with no key and one child: merge.
            const sib = parent.ptrs()[1 - pidx];
            const merged = try self.mergeChild(parent, sib);
            stack[sp - 2].ptrs()[idxs[sp - 2]] = merged;
            self.freeNode(parent);
            self.freeNode(node);
            for (stack[0 .. sp - 1]) |a| a.count -= 1;
            self.n -= 1;
            return true;
        }
        const nc: usize = parent.nchild;
        if (pidx + 1 < nc) {
            const ks = parent.keys();
            const ps = parent.ptrs();
            @memmove(ks[pidx .. nc - 1], ks[pidx + 1 .. nc]);
            @memmove(ps[pidx .. nc - 1], ps[pidx + 1 .. nc]);
        }
        parent.nchild -= 1;
        self.freeNode(node);
        for (stack[0..sp]) |a| a.count -= 1;
        self.n -= 1;
        return true;
    }

    pub fn longestPrefix(self: *const RadixTree, key: []const u8) ?Match {
        var node = self.root orelse return null;
        var pos: usize = 0;
        const kp = key.ptr;
        var best: ?Match = null;
        while (true) {
            const L: usize = node.lab_len;
            if (key.len - pos < L) break;
            if (L > 1 and !eqBytes(node.label() + 1, kp + pos + 1, L - 1)) break;
            pos += L;
            if (node.has_value != 0) best = .{ .length = pos, .value = node.value };
            if (pos == key.len) break;
            const idx = findChild(node, kp[pos]) orelse break;
            node = node.ptrs()[idx];
        }
        return best;
    }

    /// The node whose subtree holds exactly the keys starting with `prefix`.
    inline fn locate(self: *const RadixTree, prefix: []const u8) ?*Node {
        var node = self.root orelse return null;
        var pos: usize = 0;
        const kp = prefix.ptr;
        while (true) {
            const L: usize = node.lab_len;
            const rem = prefix.len - pos;
            if (rem <= L) {
                if (rem > 1 and !eqBytes(node.label() + 1, kp + pos + 1, rem - 1)) return null;
                return node;
            }
            if (L > 1 and !eqBytes(node.label() + 1, kp + pos + 1, L - 1)) return null;
            pos += L;
            const idx = findChild(node, kp[pos]) orelse return null;
            node = node.ptrs()[idx];
        }
    }

    pub fn prefixCount(self: *const RadixTree, prefix: []const u8) usize {
        const node = self.locate(prefix) orelse return 0;
        return node.count;
    }

    fn collectAll(node: *Node, out: [*]i64, w: usize) usize {
        var k = w;
        if (node.has_value != 0) {
            out[k] = node.value;
            k += 1;
        }
        const nc: usize = node.nchild;
        if (nc == 0) return k;
        const ps = node.ptrs();
        for (ps[0..nc]) |c| @prefetch(c, .{});
        for (ps[0..nc]) |c| k = collectAll(c, out, k);
        return k;
    }

    /// Writes values of node's subtree into out[w..limit]; returns new w.
    fn collectLimited(node: *Node, out: [*]i64, w: usize, limit: usize) usize {
        if (node.count <= limit - w) return collectAll(node, out, w);
        var k = w;
        if (node.has_value != 0) {
            out[k] = node.value;
            k += 1;
            if (k == limit) return k;
        }
        const nc: usize = node.nchild;
        const ps = node.ptrs();
        const pre = @min(nc, limit - k);
        for (ps[0..pre]) |c| @prefetch(c, .{});
        for (ps[0..nc]) |c| {
            k = collectLimited(c, out, k, limit);
            if (k == limit) return k;
        }
        return k;
    }

    pub fn prefixValues(self: *const RadixTree, prefix: []const u8, out_values: []i64) usize {
        if (out_values.len == 0) return 0;
        const node = self.locate(prefix) orelse return 0;
        if (node.count == 0) return 0;
        return collectLimited(node, out_values.ptr, 0, out_values.len);
    }

    pub fn len(self: *const RadixTree) usize {
        return self.n;
    }

    fn countNodes(node: *Node) usize {
        var total: usize = 1;
        const nc: usize = node.nchild;
        const ps = node.ptrs();
        for (ps[0..nc]) |c| total += countNodes(c);
        return total;
    }

    fn depth(node: *Node) usize {
        var best: usize = 0;
        const nc: usize = node.nchild;
        const ps = node.ptrs();
        for (ps[0..nc]) |c| best = @max(best, 1 + depth(c));
        return best;
    }

    pub fn nodeCount(self: *const RadixTree) usize {
        const r = self.root orelse return 1;
        return countNodes(r);
    }

    pub fn height(self: *const RadixTree) usize {
        const r = self.root orelse return 0;
        return depth(r);
    }
};
