const std = @import("std");

const MAX_HEIGHT: usize = 32;
const NUM_CLASSES: usize = 9;

// Map tower height h in [1..32] to its slab class index [0..8].
const HEIGHT_TO_CLASS: [MAX_HEIGHT + 1]u8 = blk: {
    var tbl: [MAX_HEIGHT + 1]u8 = @splat(0);
    tbl[1] = 0; // 24B (5 per 128B line, 0 splits)
    tbl[2] = 1; // 32B (4 per 128B line, 0 splits)
    tbl[3] = 2; // 40B (3 per 128B line, 0 splits)
    tbl[4] = 3; // 64B (2 per 128B line, 0 splits)
    tbl[5] = 4; // 64B (2 per 128B line, 0 splits)
    tbl[6] = 5; // 64B (2 per 128B line, 0 splits)
    tbl[7] = 6; // 80B packed
    tbl[8] = 6;
    for (9..15) |h| tbl[h] = 7; // 128B (1 per 128B line, 0 splits)
    for (15..MAX_HEIGHT + 1) |h| tbl[h] = 8; // 272B packed
    break :blk tbl;
};

const CacheLine = extern struct {
    bytes: [128]u8 align(128),
};

const ChunkHeader = struct {
    prev: ?*align(128) ChunkHeader,
    num_lines: usize,
};

const FreeNode = struct {
    next: ?*FreeNode,
};

// Every node has height h >= 1, so `next0` is always present and is followed
// contiguously by `h - 1` additional `?*Node` forward links.
const Node = extern struct {
    key: i64,
    val: i64,
    next0: ?*Node,

    inline fn nextSlice(self: *Node) [*]?*Node {
        return @ptrCast(&self.next0);
    }

    inline fn nextSliceConst(self: *const Node) [*]const ?*Node {
        return @ptrCast(&self.next0);
    }
};

// Identical prefix layout to `Node` (key at 0, val at 8, next[0] at 16) so the
// header participates in traversal without special-casing. `head.key` is never read.
const HeadNode = extern struct {
    key: i64 = 0,
    val: i64 = 0,
    next: [MAX_HEIGHT]?*Node = @splat(null),
};

const SlabPool = struct {
    free_head: ?*FreeNode = null,
    bump_ptr: [*]u8 = undefined,
    bump_rem: usize = 0,
    chunks: ?*align(128) ChunkHeader = null,
    next_chunk_lines: u32,
    max_chunk_lines: u32,
    stride: u16,
    line_limit: u16,

    fn grow(self: *SlabPool, allocator: std.mem.Allocator) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        const num_lines: usize = self.next_chunk_lines;
        const lines = try allocator.alloc(CacheLine, num_lines);
        const header: *align(128) ChunkHeader = @ptrCast(lines.ptr);
        header.* = .{
            .prev = self.chunks,
            .num_lines = num_lines,
        };
        self.chunks = header;
        self.bump_ptr = @ptrCast(lines.ptr + 1);

        const data_lines = num_lines - 1;
        if (self.line_limit == 120) {
            self.bump_rem = data_lines * (120 / @as(usize, self.stride));
        } else {
            self.bump_rem = (data_lines * 128) / @as(usize, self.stride);
        }

        self.next_chunk_lines = @min(self.max_chunk_lines, self.next_chunk_lines *| 2);
    }

    inline fn allocNode(self: *SlabPool, allocator: std.mem.Allocator) std.mem.Allocator.Error!*Node {
        if (self.free_head) |f| {
            self.free_head = f.next;
            return @ptrCast(f);
        }
        if (self.bump_rem == 0) {
            try self.grow(allocator);
        }
        const ptr = self.bump_ptr;
        var next_ptr = ptr + self.stride;
        if ((@intFromPtr(next_ptr) & 127) == self.line_limit) {
            next_ptr += 8;
        }
        self.bump_ptr = next_ptr;
        self.bump_rem -= 1;
        return @ptrCast(@alignCast(ptr));
    }

    inline fn freeNode(self: *SlabPool, node: *Node) void {
        const f: *FreeNode = @ptrCast(node);
        f.next = self.free_head;
        self.free_head = f;
    }
};

fn initPools() [NUM_CLASSES]SlabPool {
    return .{
        .{ .next_chunk_lines = 16, .max_chunk_lines = 16384, .stride = 24, .line_limit = 120 }, // h = 1
        .{ .next_chunk_lines = 16, .max_chunk_lines = 8192, .stride = 32, .line_limit = 255 }, // h = 2
        .{ .next_chunk_lines = 16, .max_chunk_lines = 4096, .stride = 40, .line_limit = 120 }, // h = 3
        .{ .next_chunk_lines = 16, .max_chunk_lines = 4096, .stride = 64, .line_limit = 255 }, // h = 4
        .{ .next_chunk_lines = 16, .max_chunk_lines = 2048, .stride = 64, .line_limit = 255 }, // h = 5
        .{ .next_chunk_lines = 16, .max_chunk_lines = 1024, .stride = 64, .line_limit = 255 }, // h = 6
        .{ .next_chunk_lines = 16, .max_chunk_lines = 1024, .stride = 80, .line_limit = 255 }, // h = 7..8
        .{ .next_chunk_lines = 16, .max_chunk_lines = 512, .stride = 128, .line_limit = 255 }, // h = 9..14
        .{ .next_chunk_lines = 16, .max_chunk_lines = 256, .stride = 272, .line_limit = 255 }, // h = 15..32
    };
}

pub const SkipList = struct {
    cur_height: usize,
    count: usize,
    rng_state: u64,
    head: HeadNode,
    allocator: std.mem.Allocator,
    pools: [NUM_CLASSES]SlabPool,

    pub fn init(allocator: std.mem.Allocator) SkipList {
        return .{
            .cur_height = 0,
            .count = 0,
            .rng_state = 0x243F6A8885A308D3,
            .head = .{},
            .allocator = allocator,
            .pools = initPools(),
        };
    }

    pub fn deinit(self: *SkipList) void {
        for (&self.pools) |*pool| {
            var ch = pool.chunks;
            while (ch) |c| {
                const prev = c.prev;
                const num_lines = c.num_lines;
                const raw: [*]CacheLine = @ptrCast(c);
                self.allocator.free(raw[0..num_lines]);
                ch = prev;
            }
            pool.chunks = null;
            pool.free_head = null;
            pool.bump_rem = 0;
        }
        self.head = .{};
        self.cur_height = 0;
        self.count = 0;
    }

    // Geometric distribution with p = 1/2, capped at MAX_HEIGHT = 32,
    // driven by a self-contained wyrand PRNG seeded with a fixed constant.
    inline fn randomHeight(self: *SkipList) usize {
        self.rng_state +%= 0xa0761d6478bd642f;
        const s = self.rng_state;
        const prod: u128 = @as(u128, s) * @as(u128, s ^ 0xe7037ed1a0b428db);
        const r: u64 = @truncate(prod ^ (prod >> 64));
        const tz: usize = @ctz(r);
        return @min(MAX_HEIGHT, tz + 1);
    }

    inline fn allocNode(self: *SkipList, h: usize) std.mem.Allocator.Error!*Node {
        const class = HEIGHT_TO_CLASS[h];
        return self.pools[class].allocNode(self.allocator);
    }

    inline fn freeNode(self: *SkipList, node: *Node, h: usize) void {
        const class = HEIGHT_TO_CLASS[h];
        self.pools[class].freeNode(node);
    }

    pub fn insert(self: *SkipList, key: i64, value: i64) std.mem.Allocator.Error!bool {
        var update: [MAX_HEIGHT]*Node = undefined;
        const h = self.cur_height;
        var curr: *Node = @ptrCast(&self.head);
        var stop: ?*Node = null;

        if (h > 0) {
            var lvl: usize = h - 1;

            while (lvl >= 4) : (lvl -= 1) {
                var next = curr.nextSlice()[lvl];
                while (next != stop) {
                    const n = next.?;
                    if (n.key < key) {
                        curr = n;
                        next = n.nextSlice()[lvl];
                    } else {
                        if (n.key == key) {
                            n.val = value;
                            return false;
                        }
                        stop = n;
                        break;
                    }
                }
                update[lvl] = curr;
            }

            while (lvl >= 1) : (lvl -= 1) {
                var nexts = curr.nextSlice();
                var next = nexts[lvl];
                while (next != stop) {
                    const down = nexts[lvl - 1];
                    if (down != next and down != stop) {
                        @prefetch(down.?, .{ .rw = .read, .locality = 3, .cache = .data });
                    }
                    const n = next.?;
                    if (n.key < key) {
                        curr = n;
                        nexts = n.nextSlice();
                        next = nexts[lvl];
                    } else {
                        if (n.key == key) {
                            n.val = value;
                            return false;
                        }
                        stop = n;
                        break;
                    }
                }
                update[lvl] = curr;
            }

            var next = curr.next0;
            while (next != stop) {
                const n = next.?;
                if (n.key < key) {
                    curr = n;
                    next = n.next0;
                } else {
                    if (n.key == key) {
                        n.val = value;
                        return false;
                    }
                    break;
                }
            }
            update[0] = curr;
        }

        const new_h = self.randomHeight();
        const node = try self.allocNode(new_h);
        node.key = key;
        node.val = value;

        const node_nexts = node.nextSlice();
        const link_up = @min(new_h, h);
        for (0..link_up) |lvl| {
            const pred_nexts = update[lvl].nextSlice();
            node_nexts[lvl] = pred_nexts[lvl];
            pred_nexts[lvl] = node;
        }
        if (new_h > h) {
            @branchHint(.unlikely);
            for (h..new_h) |lvl| {
                node_nexts[lvl] = null;
                self.head.next[lvl] = node;
            }
            self.cur_height = new_h;
        }

        self.count += 1;
        return true;
    }

    pub fn get(self: *const SkipList, key: i64) ?i64 {
        const h = self.cur_height;
        if (h == 0) return null;

        var curr: *const Node = @ptrCast(&self.head);
        var stop: ?*const Node = null;
        var lvl: usize = h - 1;

        while (lvl >= 4) : (lvl -= 1) {
            var next: ?*const Node = curr.nextSliceConst()[lvl];
            while (next != stop) {
                const n = next.?;
                if (n.key < key) {
                    curr = n;
                    next = n.nextSliceConst()[lvl];
                } else {
                    if (n.key == key) return n.val;
                    stop = n;
                    break;
                }
            }
        }

        while (lvl >= 1) : (lvl -= 1) {
            var nexts = curr.nextSliceConst();
            var next: ?*const Node = nexts[lvl];
            while (next != stop) {
                const down: ?*const Node = nexts[lvl - 1];
                if (down != next and down != stop) {
                    @prefetch(down.?, .{ .rw = .read, .locality = 3, .cache = .data });
                }
                const n = next.?;
                if (n.key < key) {
                    curr = n;
                    nexts = n.nextSliceConst();
                    next = nexts[lvl];
                } else {
                    if (n.key == key) return n.val;
                    stop = n;
                    break;
                }
            }
        }

        var next: ?*const Node = curr.next0;
        while (next != stop) {
            const n = next.?;
            if (n.key < key) {
                next = n.next0;
            } else {
                if (n.key == key) return n.val;
                return null;
            }
        }
        return null;
    }

    pub fn remove(self: *SkipList, key: i64) bool {
        const h = self.cur_height;
        if (h == 0) return false;

        // Fast path for removing the minimum key (head.next[0]): its predecessor
        // at every level it occupies is `head`.
        if (self.head.next[0]) |first| {
            const fk = first.key;
            if (fk >= key) {
                if (fk != key) return false;
                const target_nexts = first.nextSlice();
                const next_min = target_nexts[0];
                if (next_min) |nm| {
                    @prefetch(nm, .{ .rw = .read, .locality = 3, .cache = .data });
                }
                self.head.next[0] = next_min;
                var node_h: usize = 1;
                while (node_h < h and self.head.next[node_h] == first) : (node_h += 1) {
                    self.head.next[node_h] = target_nexts[node_h];
                }
                self.freeNode(first, node_h);
                self.count -= 1;
                var new_h = h;
                while (new_h > 0 and self.head.next[new_h - 1] == null) {
                    new_h -= 1;
                }
                self.cur_height = new_h;
                return true;
            }
        }

        var update: [MAX_HEIGHT]*Node = undefined;
        var curr: *Node = @ptrCast(&self.head);
        var stop: ?*Node = null;
        var lvl: usize = h - 1;

        while (lvl >= 4) : (lvl -= 1) {
            var next = curr.nextSlice()[lvl];
            while (next != stop) {
                const n = next.?;
                if (n.key < key) {
                    curr = n;
                    next = n.nextSlice()[lvl];
                } else {
                    stop = n;
                    break;
                }
            }
            update[lvl] = curr;
        }

        while (lvl >= 1) : (lvl -= 1) {
            var nexts = curr.nextSlice();
            var next = nexts[lvl];
            while (next != stop) {
                const down = nexts[lvl - 1];
                if (down != next and down != stop) {
                    @prefetch(down.?, .{ .rw = .read, .locality = 3, .cache = .data });
                }
                const n = next.?;
                if (n.key < key) {
                    curr = n;
                    nexts = n.nextSlice();
                    next = nexts[lvl];
                } else {
                    stop = n;
                    break;
                }
            }
            update[lvl] = curr;
        }

        var next = curr.next0;
        while (next != stop) {
            const n = next.?;
            if (n.key < key) {
                curr = n;
                next = n.next0;
            } else {
                stop = n;
                break;
            }
        }
        update[0] = curr;

        const target = stop orelse return false;
        if (target.key != key) return false;

        const target_nexts = target.nextSlice();
        var node_h: usize = 0;
        while (node_h < h) : (node_h += 1) {
            const pred_nexts = update[node_h].nextSlice();
            if (pred_nexts[node_h] != target) break;
            pred_nexts[node_h] = target_nexts[node_h];
        }

        self.freeNode(target, node_h);
        self.count -= 1;

        var new_h = h;
        while (new_h > 0 and self.head.next[new_h - 1] == null) {
            new_h -= 1;
        }
        self.cur_height = new_h;
        return true;
    }

    pub fn range(self: *const SkipList, lo: i64, hi: i64, out_keys: []i64, out_vals: []i64) usize {
        const limit = out_keys.len;
        const h = self.cur_height;
        if (h == 0 or lo > hi or limit == 0) return 0;

        var curr: *const Node = @ptrCast(&self.head);
        var stop: ?*const Node = null;
        var lvl: usize = h - 1;

        search: {
            while (lvl >= 4) : (lvl -= 1) {
                var next: ?*const Node = curr.nextSliceConst()[lvl];
                while (next != stop) {
                    const n = next.?;
                    if (n.key < lo) {
                        curr = n;
                        next = n.nextSliceConst()[lvl];
                    } else {
                        stop = n;
                        if (n.key == lo) break :search;
                        break;
                    }
                }
            }

            while (lvl >= 1) : (lvl -= 1) {
                var nexts = curr.nextSliceConst();
                var next: ?*const Node = nexts[lvl];
                while (next != stop) {
                    const down: ?*const Node = nexts[lvl - 1];
                    if (down != next and down != stop) {
                        @prefetch(down.?, .{ .rw = .read, .locality = 3, .cache = .data });
                    }
                    const n = next.?;
                    if (n.key < lo) {
                        curr = n;
                        nexts = n.nextSliceConst();
                        next = nexts[lvl];
                    } else {
                        stop = n;
                        if (n.key == lo) break :search;
                        break;
                    }
                }
            }

            var next: ?*const Node = curr.next0;
            while (next != stop) {
                const n = next.?;
                if (n.key < lo) {
                    next = n.next0;
                } else {
                    stop = n;
                    break;
                }
            }
        }

        var count: usize = 0;
        var scan: ?*const Node = stop;
        const ok = out_keys.ptr;
        const ov = out_vals.ptr;
        while (scan) |n| {
            const k = n.key;
            if (k > hi) break;
            const v = n.val;
            const next_node = n.next0;
            ok[count] = k;
            ov[count] = v;
            count += 1;
            if (count == limit) break;
            scan = next_node;
        }
        return count;
    }

    pub inline fn len(self: *const SkipList) usize {
        return self.count;
    }

    pub inline fn height(self: *const SkipList) usize {
        return self.cur_height;
    }

    pub fn levelCount(self: *const SkipList, level: usize) usize {
        if (level >= self.cur_height) return 0;
        var c: usize = 0;
        var cur: ?*const Node = self.head.next[level];
        while (cur) |n| : (cur = n.nextSliceConst()[level]) {
            c += 1;
        }
        return c;
    }
};
