import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * Radix tree (path-compressed byte trie) stored in a single byte[] arena.
 *
 * Every node is a fixed 128-byte block in the arena, addressed by its byte
 * offset ("base"; 0 means no node). Layout of a block:
 *
 *   0  long   value
 *   8  int    number of keys in the subtree (this node included)
 *  12  short  number of children (nk)
 *  14  byte   label length (0..255)
 *  15  byte   flags (bit 0: holds a key)
 *  16  int    id of the overflow label array (label bytes 24..), 0 = none
 *  20  int    base of the 256-entry child table in big[] (when nk > 16)
 *  24  16 B   first bytes of the children, sorted unsigned (when nk <= 16)
 *  40  24 B   first 24 bytes of the label of the edge into this node
 *  64  16 int children, parallel to the first-byte array (when nk <= 16)
 *
 * A node with more than 16 children keeps them in a 256-entry table indexed
 * by byte in the separate int[] pool big[].
 */
public final class RadixTree {
    private static final VarHandle LONG =
        MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN);
    private static final VarHandle INT =
        MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
    private static final VarHandle SHORT =
        MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN);

    private static final int NODE = 128;
    // Large arrays start at a region boundary; with a 16-byte array header this
    // puts every node block on a 128-byte cache line boundary.
    private static final int PAD = 112;

    private static final int VAL = 0;
    private static final int CNT = 8;
    private static final int NK = 12;
    private static final int LLEN = 14;
    private static final int FLAGS = 15;
    private static final int OVF = 16;
    private static final int BIG = 20;
    private static final int KEYS = 24;
    private static final int LAB = 40;
    private static final int INL = 24;
    private static final int KIDS = 64;
    private static final int SMALL = 16;

    private static final long LO = 0x0101010101010101L;
    private static final long HI = 0x8080808080808080L;

    private byte[] A;
    private int top;       // next unused byte offset in A
    private int freeNodes; // free list of node blocks (link in VAL), 0 = empty
    private final int root;
    private int size;

    private int[] big = new int[0];
    private int bigTop;
    private int[] bigFree = new int[4];
    private int bigFreeTop;

    private byte[][] ovf = new byte[16][];
    private int ovfTop = 1;
    private int[] ovfFree = new int[16];
    private int ovfFreeTop;

    private final int[] path = new int[264];
    private final byte[] scratch = new byte[512];

    public RadixTree() {
        A = new byte[PAD + 64 * NODE];
        top = PAD;
        root = newNode();
    }

    // ------------------------------------------------------------ helpers

    private static long readLong(byte[] buf, int p) {
        if (p + 8 <= buf.length) return (long) LONG.get(buf, p);
        long r = 0;
        int lim = Math.min(buf.length - p, 8);
        for (int k = 0; k < lim; k++) r |= (buf[p + k] & 0xFFL) << (k << 3);
        return r;
    }

    private static int nk(byte[] A, int n) {
        return (short) SHORT.get(A, n + NK);
    }

    private static int llen(byte[] A, int n) {
        return A[n + LLEN] & 0xFF;
    }

    /** Index of byte b among the first n <= 16 child bytes of node n, or -1. */
    private static int findIdx(byte[] A, int n, int nk, int b) {
        long pat = (b & 0xFFL) * LO;
        long x = (long) LONG.get(A, n + KEYS) ^ pat;
        long t = (x - LO) & ~x & HI;
        if (nk < 8) t &= (1L << (nk << 3)) - 1;
        if (t != 0) return Long.numberOfTrailingZeros(t) >>> 3;
        if (nk <= 8) return -1;
        x = (long) LONG.get(A, n + KEYS + 8) ^ pat;
        t = (x - LO) & ~x & HI;
        if (nk < 16) t &= (1L << ((nk - 8) << 3)) - 1;
        if (t != 0) return 8 + (Long.numberOfTrailingZeros(t) >>> 3);
        return -1;
    }

    private int child(byte[] A, int n, int b) {
        int nk = nk(A, n);
        if (nk > SMALL) return big[(int) INT.get(A, n + BIG) + (b & 0xFF)];
        int idx = findIdx(A, n, nk, b);
        return idx < 0 ? 0 : (int) INT.get(A, n + KIDS + (idx << 2));
    }

    /** Length of the common prefix of the label of c and buf[i..i+max), max <= label length. */
    private int lcp(byte[] A, int c, byte[] buf, int i, int max) {
        int lim = max < INL ? max : INL;
        int lb = c + LAB;
        for (int k = 0; k < lim; k += 8) {
            long x = (long) LONG.get(A, lb + k) ^ readLong(buf, i + k);
            int rem = lim - k;
            if (rem < 8) x &= (1L << (rem << 3)) - 1;
            if (x != 0) return k + (Long.numberOfTrailingZeros(x) >>> 3);
        }
        if (max <= INL) return max;
        int mm = Arrays.mismatch(buf, i + INL, i + max, ovf[(int) INT.get(A, c + OVF)], 0, max - INL);
        return mm < 0 ? max : INL + mm;
    }

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

    private int newNode() {
        int n = freeNodes;
        byte[] A = this.A;
        if (n != 0) {
            freeNodes = (int) (long) LONG.get(A, n + VAL);
        } else {
            if (top + NODE > A.length) {
                long cap = (long) A.length + (A.length >> 1);
                if (cap > Integer.MAX_VALUE - 64) cap = Integer.MAX_VALUE - 64;
                if (top + NODE > cap) throw new OutOfMemoryError("radix tree arena full");
                A = this.A = Arrays.copyOf(A, (int) cap);
            }
            n = top;
            top += NODE;
        }
        LONG.set(A, n, 0L);
        LONG.set(A, n + 8, 0L);
        LONG.set(A, n + 16, 0L);
        return n;
    }

    private void freeNode(int n) {
        byte[] A = this.A;
        int id = (int) INT.get(A, n + OVF);
        if (id != 0) freeOvf(id);
        if (nk(A, n) > SMALL) freeBig((int) INT.get(A, n + BIG));
        LONG.set(A, n + VAL, (long) freeNodes);
        freeNodes = n;
    }

    private int allocBig() {
        if (bigFreeTop > 0) return bigFree[--bigFreeTop];
        if (bigTop + 256 > big.length) {
            big = Arrays.copyOf(big, Math.max(1024, big.length * 2));
        }
        int b = bigTop;
        bigTop += 256;
        return b;
    }

    private void freeBig(int b) {
        Arrays.fill(big, b, b + 256, 0);
        if (bigFreeTop == bigFree.length) bigFree = Arrays.copyOf(bigFree, bigFree.length * 2);
        bigFree[bigFreeTop++] = b;
    }

    private int allocOvf() {
        if (ovfFreeTop > 0) return ovfFree[--ovfFreeTop];
        if (ovfTop == ovf.length) ovf = Arrays.copyOf(ovf, ovf.length * 2);
        return ovfTop++;
    }

    private void freeOvf(int id) {
        ovf[id] = null;
        if (ovfFreeTop == ovfFree.length) ovfFree = Arrays.copyOf(ovfFree, ovfFree.length * 2);
        ovfFree[ovfFreeTop++] = id;
    }

    // ------------------------------------------------------------ labels

    private void setLabel(int n, byte[] src, int off, int len) {
        byte[] A = this.A;
        A[n + LLEN] = (byte) len;
        System.arraycopy(src, off, A, n + LAB, Math.min(len, INL));
        int id = (int) INT.get(A, n + OVF);
        if (len > INL) {
            if (id == 0) {
                id = allocOvf();
                INT.set(A, n + OVF, id);
            }
            ovf[id] = Arrays.copyOfRange(src, off + INL, off + len);
        } else if (id != 0) {
            freeOvf(id);
            INT.set(A, n + OVF, 0);
        }
    }

    /** Copy the label of n to dst[pos..], return its length. */
    private int getLabel(int n, byte[] dst, int pos) {
        byte[] A = this.A;
        int len = llen(A, n);
        System.arraycopy(A, n + LAB, dst, pos, Math.min(len, INL));
        if (len > INL) System.arraycopy(ovf[(int) INT.get(A, n + OVF)], 0, dst, pos + INL, len - INL);
        return len;
    }

    // ------------------------------------------------------------ children

    private void addChild(int n, byte b, int c) {
        byte[] A = this.A;
        int nk = nk(A, n);
        int ub = b & 0xFF;
        if (nk < SMALL) {
            int pos = 0;
            while (pos < nk && (A[n + KEYS + pos] & 0xFF) < ub) pos++;
            int mv = nk - pos;
            if (mv > 0) {
                System.arraycopy(A, n + KEYS + pos, A, n + KEYS + pos + 1, mv);
                System.arraycopy(A, n + KIDS + (pos << 2), A, n + KIDS + (pos << 2) + 4, mv << 2);
            }
            A[n + KEYS + pos] = b;
            INT.set(A, n + KIDS + (pos << 2), c);
        } else if (nk == SMALL) {
            int blk = allocBig();
            int[] big = this.big;
            for (int k = 0; k < SMALL; k++) {
                big[blk + (A[n + KEYS + k] & 0xFF)] = (int) INT.get(A, n + KIDS + (k << 2));
            }
            big[blk + ub] = c;
            INT.set(A, n + BIG, blk);
        } else {
            big[(int) INT.get(A, n + BIG) + ub] = c;
        }
        SHORT.set(A, n + NK, (short) (nk + 1));
    }

    private void removeChild(int n, byte b) {
        byte[] A = this.A;
        int nk = nk(A, n);
        if (nk <= SMALL) {
            int idx = findIdx(A, n, nk, b);
            int mv = nk - 1 - idx;
            if (mv > 0) {
                System.arraycopy(A, n + KEYS + idx + 1, A, n + KEYS + idx, mv);
                System.arraycopy(A, n + KIDS + (idx << 2) + 4, A, n + KIDS + (idx << 2), mv << 2);
            }
        } else {
            int blk = (int) INT.get(A, n + BIG);
            int[] big = this.big;
            big[blk + (b & 0xFF)] = 0;
            if (nk - 1 == SMALL) {
                int k = 0;
                for (int x = 0; x < 256; x++) {
                    int c = big[blk + x];
                    if (c != 0) {
                        A[n + KEYS + k] = (byte) x;
                        INT.set(A, n + KIDS + (k << 2), c);
                        k++;
                    }
                }
                freeBig(blk);
            }
        }
        SHORT.set(A, n + NK, (short) (nk - 1));
    }

    private void replaceChild(int n, byte b, int c) {
        byte[] A = this.A;
        int nk = nk(A, n);
        if (nk > SMALL) {
            big[(int) INT.get(A, n + BIG) + (b & 0xFF)] = c;
        } else {
            INT.set(A, n + KIDS + (findIdx(A, n, nk, b) << 2), c);
        }
    }

    private int onlyChild(int n) {
        byte[] A = this.A;
        if (nk(A, n) <= SMALL) return (int) INT.get(A, n + KIDS);
        int blk = (int) INT.get(A, n + BIG);
        for (int x = 0; x < 256; x++) if (big[blk + x] != 0) return big[blk + x];
        return 0;
    }

    /** Merge node m (no key, one child) into its child; g is m's parent. */
    private void merge(int g, int m) {
        int c = onlyChild(m);
        byte[] s = scratch;
        int lm = getLabel(m, s, 0);
        int lc = getLabel(c, s, lm);
        setLabel(c, s, 0, lm + lc);
        replaceChild(g, s[0], c);
        freeNode(m);
    }

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

    public boolean insert(byte[] buf, int off, int len, long value) {
        final int[] path = this.path;
        int end = off + len;
        int i = off;
        int n = root;
        int d = 0;
        while (true) {
            path[d++] = n;
            byte[] A = this.A;
            if (i == end) {
                if ((A[n + FLAGS] & 1) != 0) {
                    LONG.set(A, n + VAL, value);
                    return false;
                }
                A[n + FLAGS] = 1;
                LONG.set(A, n + VAL, value);
                break;
            }
            byte b = buf[i];
            int c = child(A, n, b);
            if (c == 0) {
                int leaf = newLeaf(buf, i, end - i, value);
                addChild(n, b, leaf);
                break;
            }
            int ll = llen(A, c);
            int rem = end - i;
            int m = lcp(A, c, buf, i, ll < rem ? ll : rem);
            if (m == ll) {
                i += ll;
                n = c;
                continue;
            }
            // Split the edge into c after m bytes.
            int mid = newNode();
            byte[] s = scratch;
            getLabel(c, s, 0);
            setLabel(mid, s, 0, m);
            setLabel(c, s, m, ll - m);
            A = this.A;
            INT.set(A, mid + CNT, (int) INT.get(A, c + CNT));
            A[mid + KEYS] = s[m];
            INT.set(A, mid + KIDS, c);
            SHORT.set(A, mid + NK, (short) 1);
            replaceChild(n, b, mid);
            if (i + m == end) {
                A[mid + FLAGS] = 1;
                LONG.set(A, mid + VAL, value);
            } else {
                int leaf = newLeaf(buf, i + m, end - i - m, value);
                addChild(mid, buf[i + m], leaf);
            }
            path[d++] = mid;
            break;
        }
        byte[] A = this.A;
        for (int k = 0; k < d; k++) {
            int p = path[k];
            INT.set(A, p + CNT, (int) INT.get(A, p + CNT) + 1);
        }
        size++;
        return true;
    }

    private int newLeaf(byte[] buf, int off, int len, long value) {
        int leaf = newNode();
        setLabel(leaf, buf, off, len);
        byte[] A = this.A;
        LONG.set(A, leaf + VAL, value);
        INT.set(A, leaf + CNT, 1);
        A[leaf + FLAGS] = 1;
        return leaf;
    }

    public boolean get(byte[] buf, int off, int len, long[] out) {
        final byte[] A = this.A;
        int end = off + len;
        int i = off;
        int n = root;
        while (i < end) {
            int c = child(A, n, buf[i]);
            if (c == 0) return false;
            int ll = llen(A, c);
            if (ll > end - i || lcp(A, c, buf, i, ll) != ll) return false;
            i += ll;
            n = c;
        }
        if ((A[n + FLAGS] & 1) == 0) return false;
        out[0] = (long) LONG.get(A, n + VAL);
        return true;
    }

    public boolean remove(byte[] buf, int off, int len) {
        final int[] path = this.path;
        byte[] A = this.A;
        int end = off + len;
        int i = off;
        int n = root;
        int d = 0;
        path[d++] = n;
        while (i < end) {
            int c = child(A, n, buf[i]);
            if (c == 0) return false;
            int ll = llen(A, c);
            if (ll > end - i || lcp(A, c, buf, i, ll) != ll) return false;
            i += ll;
            n = c;
            path[d++] = n;
        }
        if ((A[n + FLAGS] & 1) == 0) return false;
        A[n + FLAGS] = 0;
        for (int k = 0; k < d; k++) {
            int p = path[k];
            INT.set(A, p + CNT, (int) INT.get(A, p + CNT) - 1);
        }
        size--;
        if (d == 1) return true; // the root
        int p = path[d - 2];
        int nk = nk(A, n);
        if (nk == 0) {
            removeChild(p, A[n + LAB]);
            freeNode(n);
            if (d >= 3 && (A[p + FLAGS] & 1) == 0 && nk(A, p) == 1) merge(path[d - 3], p);
        } else if (nk == 1) {
            merge(p, n);
        }
        return true;
    }

    public int longestPrefix(byte[] buf, int off, int len, long[] out) {
        final byte[] A = this.A;
        int end = off + len;
        int i = off;
        int n = root;
        int best = -1;
        long bestVal = 0;
        if ((A[n + FLAGS] & 1) != 0) {
            best = 0;
            bestVal = (long) LONG.get(A, n + VAL);
        }
        while (i < end) {
            int c = child(A, n, buf[i]);
            if (c == 0) break;
            int ll = llen(A, c);
            if (ll > end - i || lcp(A, c, buf, i, ll) != ll) break;
            i += ll;
            n = c;
            if ((A[n + FLAGS] & 1) != 0) {
                best = i - off;
                bestVal = (long) LONG.get(A, n + VAL);
            }
        }
        if (best >= 0) out[0] = bestVal;
        return best;
    }

    /** The node whose subtree holds exactly the keys starting with the prefix, or 0. */
    private int locate(byte[] A, byte[] buf, int off, int len) {
        int end = off + len;
        int i = off;
        int n = root;
        while (i < end) {
            int c = child(A, n, buf[i]);
            if (c == 0) return 0;
            int ll = llen(A, c);
            int rem = end - i;
            if (rem <= ll) return lcp(A, c, buf, i, rem) == rem ? c : 0;
            if (lcp(A, c, buf, i, ll) != ll) return 0;
            i += ll;
            n = c;
        }
        return n;
    }

    public int prefixCount(byte[] buf, int off, int len) {
        final byte[] A = this.A;
        int n = locate(A, buf, off, len);
        return n == 0 ? 0 : (int) INT.get(A, n + CNT);
    }

    public int prefixValues(byte[] buf, int off, int len, long[] outValues, int limit) {
        if (limit <= 0) return 0;
        final byte[] A = this.A;
        int n = locate(A, buf, off, len);
        if (n == 0) return 0;
        if ((int) INT.get(A, n + CNT) <= limit) return collectAll(A, n, outValues, 0);
        return collect(A, n, outValues, 0, limit);
    }

    private int collect(byte[] A, int n, long[] out, int pos, int limit) {
        if ((int) INT.get(A, n + CNT) <= limit - pos) return collectAll(A, n, out, pos);
        if ((A[n + FLAGS] & 1) != 0) {
            out[pos++] = (long) LONG.get(A, n + VAL);
            if (pos >= limit) return pos;
        }
        int nk = nk(A, n);
        if (nk <= SMALL) {
            for (int k = 0; k < nk; k++) {
                pos = collect(A, (int) INT.get(A, n + KIDS + (k << 2)), out, pos, limit);
                if (pos >= limit) return pos;
            }
        } else {
            int[] big = this.big;
            int blk = (int) INT.get(A, n + BIG);
            for (int x = 0; x < 256; x++) {
                int c = big[blk + x];
                if (c != 0) {
                    pos = collect(A, c, out, pos, limit);
                    if (pos >= limit) return pos;
                }
            }
        }
        return pos;
    }

    private int collectAll(byte[] A, int n, long[] out, int pos) {
        if ((A[n + FLAGS] & 1) != 0) out[pos++] = (long) LONG.get(A, n + VAL);
        int nk = nk(A, n);
        if (nk <= SMALL) {
            for (int k = 0; k < nk; k++) {
                pos = collectAll(A, (int) INT.get(A, n + KIDS + (k << 2)), out, pos);
            }
        } else {
            int[] big = this.big;
            int blk = (int) INT.get(A, n + BIG);
            for (int x = 0; x < 256; x++) {
                int c = big[blk + x];
                if (c != 0) pos = collectAll(A, c, out, pos);
            }
        }
        return pos;
    }

    public int size() {
        return size;
    }

    public int nodeCount() {
        return countNodes(root);
    }

    public int height() {
        return heightOf(root);
    }

    private int countNodes(int n) {
        byte[] A = this.A;
        int r = 1;
        int nk = nk(A, n);
        if (nk <= SMALL) {
            for (int k = 0; k < nk; k++) r += countNodes((int) INT.get(A, n + KIDS + (k << 2)));
        } else {
            int blk = (int) INT.get(A, n + BIG);
            for (int x = 0; x < 256; x++) if (big[blk + x] != 0) r += countNodes(big[blk + x]);
        }
        return r;
    }

    private int heightOf(int n) {
        byte[] A = this.A;
        int h = 0;
        int nk = nk(A, n);
        if (nk <= SMALL) {
            for (int k = 0; k < nk; k++) h = Math.max(h, 1 + heightOf((int) INT.get(A, n + KIDS + (k << 2))));
        } else {
            int blk = (int) INT.get(A, n + BIG);
            for (int x = 0; x < 256; x++) if (big[blk + x] != 0) h = Math.max(h, 1 + heightOf(big[blk + x]));
        }
        return h;
    }
}
