#include "rtree.hpp"

#include <algorithm>
#include <cstring>

using std::int32_t;
using std::int64_t;
using std::uint32_t;
using std::uint64_t;
using Node = RTree::Node;

namespace {

constexpr int M = RTree::M;
constexpr int MINF = RTree::MINF;
constexpr int MAX_DEPTH = 64;

inline uint32_t valid_mask(int count) { return (1u << count) - 1u; }

inline void prefetch_node(const Node* p) {
    const char* c = reinterpret_cast<const char*>(p);
    __builtin_prefetch(c);
    __builtin_prefetch(c + 128);
    __builtin_prefetch(c + 256);
}

// Slots whose rectangle intersects the query.
inline uint32_t intersect_mask(const Node& n, int32_t qx0, int32_t qy0, int32_t qx1,
                               int32_t qy1) {
    uint32_t m = 0;
    for (int i = 0; i < M; i++) {
        bool b = (n.x0[i] <= qx1) & (qx0 <= n.x1[i]) & (n.y0[i] <= qy1) & (qy0 <= n.y1[i]);
        m |= (uint32_t)b << i;
    }
    return m & valid_mask(n.count);
}

// Slots whose rectangle contains the query rectangle.
inline uint32_t contain_mask(const Node& n, int32_t qx0, int32_t qy0, int32_t qx1,
                             int32_t qy1) {
    uint32_t m = 0;
    for (int i = 0; i < M; i++) {
        bool b = (n.x0[i] <= qx0) & (n.y0[i] <= qy0) & (qx1 <= n.x1[i]) & (qy1 <= n.y1[i]);
        m |= (uint32_t)b << i;
    }
    return m & valid_mask(n.count);
}

inline void node_bbox(const Node& n, int32_t& bx0, int32_t& by0, int32_t& bx1, int32_t& by1) {
    int32_t a = n.x0[0], b = n.y0[0], c = n.x1[0], d = n.y1[0];
    for (int i = 1; i < n.count; i++) {
        a = std::min(a, n.x0[i]);
        b = std::min(b, n.y0[i]);
        c = std::max(c, n.x1[i]);
        d = std::max(d, n.y1[i]);
    }
    bx0 = a;
    by0 = b;
    bx1 = c;
    by1 = d;
}

inline uint64_t rect_area(int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
    return (uint64_t)(uint32_t)(x1 - x0) * (uint64_t)(uint32_t)(y1 - y0);
}

// ChooseSubtree: least enlargement, then smallest area, then lowest slot.
inline int choose_subtree(const Node& n, int32_t rx0, int32_t ry0, int32_t rx1, int32_t ry1) {
    uint64_t enl[M], area[M];
    for (int i = 0; i < M; i++) {
        uint32_t w = (uint32_t)(n.x1[i] - n.x0[i]);
        uint32_t h = (uint32_t)(n.y1[i] - n.y0[i]);
        uint64_t a = (uint64_t)w * h;
        uint32_t W = (uint32_t)(std::max(n.x1[i], rx1) - std::min(n.x0[i], rx0));
        uint32_t H = (uint32_t)(std::max(n.y1[i], ry1) - std::min(n.y0[i], ry0));
        area[i] = a;
        enl[i] = (uint64_t)W * H - a;
    }
    int best = 0;
    uint64_t be = enl[0], ba = area[0];
    const int cnt = n.count;
    for (int i = 1; i < cnt; i++) {
        uint64_t e = enl[i], a = area[i];
        if (e < be || (e == be && a < ba)) {
            best = i;
            be = e;
            ba = a;
        }
    }
    return best;
}

inline void append_entry(Node& n, int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t ref) {
    int c = n.count;
    n.x0[c] = x0;
    n.y0[c] = y0;
    n.x1[c] = x1;
    n.y1[c] = y1;
    n.ref[c] = ref;
    n.count = c + 1;
}

inline void remove_slot(Node& n, int s) {
    int last = n.count - 1;
    n.x0[s] = n.x0[last];
    n.y0[s] = n.y0[last];
    n.x1[s] = n.x1[last];
    n.y1[s] = n.y1[last];
    n.ref[s] = n.ref[last];
    n.count = last;
}

inline void set_rect(Node& n, int s, int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
    n.x0[s] = x0;
    n.y0[s] = y0;
    n.x1[s] = x1;
    n.y1[s] = y1;
}

}  // namespace

RTree::RTree() {
    reserve_nodes(64);
    root_ = alloc_node(0);
}

RTree::~RTree() { delete[] pool_; }

void RTree::reserve_nodes(uint32_t extra) {
    if (used_ + extra <= cap_) return;
    uint32_t ncap = std::max<uint32_t>(cap_ * 2, used_ + extra);
    Node* p = new Node[ncap];
    if (pool_) {
        std::memcpy(static_cast<void*>(p), static_cast<const void*>(pool_),
                    (size_t)used_ * sizeof(Node));
        delete[] pool_;
    }
    pool_ = p;
    cap_ = ncap;
}

uint32_t RTree::alloc_node(int32_t level) {
    uint32_t n;
    if (!free_.empty()) {
        n = free_.back();
        free_.pop_back();
    } else {
        n = used_++;
    }
    Node& N = pool_[n];
    std::memset(static_cast<void*>(&N), 0, sizeof(Node));
    N.level = level;
    return n;
}

// Quadratic split of node n's 16 entries plus one extra entry into n and nn.
void RTree::split(uint32_t n, uint32_t nn, int32_t ex0, int32_t ey0, int32_t ex1, int32_t ey1,
                  int32_t eref) {
    constexpr int T = M + 1;
    Node& A = pool_[n];
    Node& B = pool_[nn];
    int32_t X0[T], Y0[T], X1[T], Y1[T], R[T];
    for (int i = 0; i < M; i++) {
        X0[i] = A.x0[i];
        Y0[i] = A.y0[i];
        X1[i] = A.x1[i];
        Y1[i] = A.y1[i];
        R[i] = A.ref[i];
    }
    X0[M] = ex0;
    Y0[M] = ey0;
    X1[M] = ex1;
    Y1[M] = ey1;
    R[M] = eref;

    int64_t area[T];
    for (int i = 0; i < T; i++) area[i] = (int64_t)rect_area(X0[i], Y0[i], X1[i], Y1[i]);

    // PickSeeds.
    int s1 = 0, s2 = 1;
    int64_t bestd = INT64_MIN;
    for (int i = 0; i < T - 1; i++) {
        for (int j = i + 1; j < T; j++) {
            int64_t ja = (int64_t)rect_area(std::min(X0[i], X0[j]), std::min(Y0[i], Y0[j]),
                                            std::max(X1[i], X1[j]), std::max(Y1[i], Y1[j]));
            int64_t d = ja - area[i] - area[j];
            if (d > bestd) {
                bestd = d;
                s1 = i;
                s2 = j;
            }
        }
    }

    signed char grp[T];
    for (int i = 0; i < T; i++) grp[i] = -1;
    grp[s1] = 0;
    grp[s2] = 1;
    int32_t g0x0 = X0[s1], g0y0 = Y0[s1], g0x1 = X1[s1], g0y1 = Y1[s1];
    int32_t g1x0 = X0[s2], g1y0 = Y0[s2], g1x1 = X1[s2], g1y1 = Y1[s2];
    int64_t a0 = area[s1], a1 = area[s2];
    int c0 = 1, c1 = 1;
    int remaining = T - 2;

    while (remaining > 0) {
        if (c0 + remaining <= MINF || c1 + remaining <= MINF) {
            signed char g = (c0 + remaining <= MINF) ? 0 : 1;
            for (int i = 0; i < T; i++)
                if (grp[i] < 0) grp[i] = g;
            break;
        }
        // PickNext.
        int pick = -1;
        int64_t bestdiff = -1, pd0 = 0, pd1 = 0;
        for (int i = 0; i < T; i++) {
            if (grp[i] >= 0) continue;
            int64_t d0 = (int64_t)rect_area(std::min(g0x0, X0[i]), std::min(g0y0, Y0[i]),
                                            std::max(g0x1, X1[i]), std::max(g0y1, Y1[i])) -
                         a0;
            int64_t d1 = (int64_t)rect_area(std::min(g1x0, X0[i]), std::min(g1y0, Y0[i]),
                                            std::max(g1x1, X1[i]), std::max(g1y1, Y1[i])) -
                         a1;
            int64_t diff = d0 > d1 ? d0 - d1 : d1 - d0;
            if (diff > bestdiff) {
                bestdiff = diff;
                pick = i;
                pd0 = d0;
                pd1 = d1;
            }
        }
        int g;
        if (pd0 < pd1) g = 0;
        else if (pd1 < pd0) g = 1;
        else if (a0 < a1) g = 0;
        else if (a1 < a0) g = 1;
        else g = (c0 <= c1) ? 0 : 1;
        grp[pick] = (signed char)g;
        if (g == 0) {
            g0x0 = std::min(g0x0, X0[pick]);
            g0y0 = std::min(g0y0, Y0[pick]);
            g0x1 = std::max(g0x1, X1[pick]);
            g0y1 = std::max(g0y1, Y1[pick]);
            a0 = (int64_t)rect_area(g0x0, g0y0, g0x1, g0y1);
            c0++;
        } else {
            g1x0 = std::min(g1x0, X0[pick]);
            g1y0 = std::min(g1y0, Y0[pick]);
            g1x1 = std::max(g1x1, X1[pick]);
            g1y1 = std::max(g1y1, Y1[pick]);
            a1 = (int64_t)rect_area(g1x0, g1y0, g1x1, g1y1);
            c1++;
        }
        remaining--;
    }

    A.count = 0;
    B.count = 0;
    for (int i = 0; i < T; i++) {
        Node& D = grp[i] == 0 ? A : B;
        append_entry(D, X0[i], Y0[i], X1[i], Y1[i], R[i]);
    }
}

// Insert an entry (rectangle, ref) into a node at the given level
// (0 = leaf entry, otherwise ref is a child node at level - 1).
void RTree::insert_at(int32_t level, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
                      int32_t ref) {
    reserve_nodes((uint32_t)pool_[root_].level + 3);

    uint32_t pathN[MAX_DEPTH];
    int pathS[MAX_DEPTH];
    int depth = 0;
    uint32_t n = root_;
    while (pool_[n].level > level) {
        Node& N = pool_[n];
        int s = choose_subtree(N, x0, y0, x1, y1);
        N.x0[s] = std::min(N.x0[s], x0);
        N.y0[s] = std::min(N.y0[s], y0);
        N.x1[s] = std::max(N.x1[s], x1);
        N.y1[s] = std::max(N.y1[s], y1);
        pathN[depth] = n;
        pathS[depth] = s;
        depth++;
        uint32_t c = (uint32_t)N.ref[s];
        prefetch_node(&pool_[c]);
        n = c;
    }

    {
        Node& N = pool_[n];
        if (N.count < M) {
            append_entry(N, x0, y0, x1, y1, ref);
            return;
        }
    }

    // Overflow: split and propagate upward.
    uint32_t nn = alloc_node(pool_[n].level);
    split(n, nn, x0, y0, x1, y1, ref);
    while (depth > 0) {
        depth--;
        uint32_t p = pathN[depth];
        int s = pathS[depth];
        int32_t bx0, by0, bx1, by1;
        node_bbox(pool_[n], bx0, by0, bx1, by1);
        Node& P = pool_[p];
        set_rect(P, s, bx0, by0, bx1, by1);
        node_bbox(pool_[nn], bx0, by0, bx1, by1);
        if (P.count < M) {
            append_entry(P, bx0, by0, bx1, by1, (int32_t)nn);
            return;
        }
        uint32_t nn2 = alloc_node(P.level);
        split(p, nn2, bx0, by0, bx1, by1, (int32_t)nn);
        n = p;
        nn = nn2;
    }

    // The root was split: grow a new root.
    uint32_t r = alloc_node(pool_[n].level + 1);
    int32_t bx0, by0, bx1, by1;
    node_bbox(pool_[n], bx0, by0, bx1, by1);
    append_entry(pool_[r], bx0, by0, bx1, by1, (int32_t)n);
    node_bbox(pool_[nn], bx0, by0, bx1, by1);
    append_entry(pool_[r], bx0, by0, bx1, by1, (int32_t)nn);
    root_ = r;
}

void RTree::insert(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    insert_at(0, x0, y0, x1, y1, id);
    size_++;
}

bool RTree::remove(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t id) {
    if (size_ == 0) return false;

    // Depth-first search for the leaf, one frame per level.
    uint32_t fN[MAX_DEPTH];
    uint32_t fMask[MAX_DEPTH];
    int fSlot[MAX_DEPTH];
    int d = 0;
    fN[0] = root_;
    fMask[0] = 0;
    int leafDepth = -1, leafSlot = -1;
    {
        const Node& R = pool_[root_];
        if (R.level > 0) fMask[0] = contain_mask(R, x0, y0, x1, y1);
    }
    // Every frame on the stack is an internal node except possibly the top.
    for (;;) {
        const Node& N = pool_[fN[d]];
        if (N.level == 0) {
            uint32_t m = 0;
            for (int i = 0; i < M; i++) m |= (uint32_t)(N.ref[i] == id) << i;
            m &= valid_mask(N.count);
            while (m) {
                int i = __builtin_ctz(m);
                m &= m - 1;
                if (N.x0[i] == x0 && N.y0[i] == y0 && N.x1[i] == x1 && N.y1[i] == y1) {
                    leafDepth = d;
                    leafSlot = i;
                    break;
                }
            }
            if (leafDepth >= 0) break;
            if (d == 0) return false;
            d--;
            continue;
        }
        uint32_t m = fMask[d];
        if (m == 0) {
            if (d == 0) return false;
            d--;
            continue;
        }
        int s = __builtin_ctz(m);
        fMask[d] = m & (m - 1);
        fSlot[d] = s;
        uint32_t c = (uint32_t)N.ref[s];
        const Node& C = pool_[c];
        fN[d + 1] = c;
        fMask[d + 1] = C.level > 0 ? contain_mask(C, x0, y0, x1, y1) : 0;
        d++;
    }

    remove_slot(pool_[fN[leafDepth]], leafSlot);
    size_--;

    // CondenseTree.
    uint32_t orphans[MAX_DEPTH];
    int norph = 0;
    for (int k = leafDepth; k > 0; k--) {
        uint32_t n = fN[k];
        Node& P = pool_[fN[k - 1]];
        int s = fSlot[k - 1];
        const Node& N = pool_[n];
        if (N.count < MINF) {
            remove_slot(P, s);
            orphans[norph++] = n;
        } else {
            int32_t bx0, by0, bx1, by1;
            node_bbox(N, bx0, by0, bx1, by1);
            if (bx0 == P.x0[s] && by0 == P.y0[s] && bx1 == P.x1[s] && by1 == P.y1[s]) break;
            set_rect(P, s, bx0, by0, bx1, by1);
        }
    }

    // Reinsert the entries of removed nodes at their own level.
    for (int o = 0; o < norph; o++) {
        Node copy = pool_[orphans[o]];
        free_node(orphans[o]);
        for (int i = 0; i < copy.count; i++) {
            insert_at(copy.level, copy.x0[i], copy.y0[i], copy.x1[i], copy.y1[i], copy.ref[i]);
        }
    }

    // Shorten the tree.
    while (pool_[root_].level > 0 && pool_[root_].count == 1) {
        uint32_t old = root_;
        root_ = (uint32_t)pool_[old].ref[0];
        free_node(old);
    }
    return true;
}

std::size_t RTree::search(int32_t qx0, int32_t qy0, int32_t qx1, int32_t qy1, int32_t* out,
                          std::size_t cap) const {
    if (size_ == 0) return 0;
    uint32_t stack[M * MAX_DEPTH];
    int sp = 0;
    stack[sp++] = root_;
    std::size_t total = 0, written = 0;
    const Node* pool = pool_;
    while (sp > 0) {
        const Node& N = pool[stack[--sp]];
        uint32_t m = intersect_mask(N, qx0, qy0, qx1, qy1);
        if (N.level == 0) {
            std::size_t pc = (std::size_t)__builtin_popcount(m);
            if (written + pc <= cap) {
                while (m) {
                    int i = __builtin_ctz(m);
                    m &= m - 1;
                    out[written++] = N.ref[i];
                }
            } else {
                while (m && written < cap) {
                    int i = __builtin_ctz(m);
                    m &= m - 1;
                    out[written++] = N.ref[i];
                }
            }
            total += pc;
        } else {
            while (m) {
                int i = __builtin_ctz(m);
                m &= m - 1;
                uint32_t c = (uint32_t)N.ref[i];
                prefetch_node(&pool[c]);
                stack[sp++] = c;
            }
        }
    }
    return total;
}

std::size_t RTree::nearest(int32_t x, int32_t y, std::size_t k, int32_t* out) const {
    if (k == 0 || size_ == 0) return 0;
    const std::size_t kk = std::min(k, size_);
    if (rd_.size() < kk) {
        rd_.resize(kk);
        rid_.resize(kk);
    }
    uint64_t* rd = rd_.data();
    int32_t* rid = rid_.data();
    std::size_t cnt = 0;
    uint64_t worst = UINT64_MAX;  // distance of the kk-th result once full

    auto cmp = [](const HeapItem& a, const HeapItem& b) { return a.d > b.d; };
    std::vector<HeapItem>& heap = heap_;
    heap.clear();
    heap.push_back({0, root_});
    const Node* pool = pool_;

    while (!heap.empty()) {
        HeapItem top = heap.front();
        if (top.d > worst) break;
        std::pop_heap(heap.begin(), heap.end(), cmp);
        heap.pop_back();
        const Node& N = pool[top.node];
        uint64_t dist[M];
        for (int i = 0; i < M; i++) {
            int32_t dx = std::max(std::max(N.x0[i] - x, x - N.x1[i]), 0);
            int32_t dy = std::max(std::max(N.y0[i] - y, y - N.y1[i]), 0);
            dist[i] = (uint64_t)(uint32_t)dx * (uint32_t)dx + (uint64_t)(uint32_t)dy * (uint32_t)dy;
        }
        const int c = N.count;
        if (N.level == 0) {
            for (int i = 0; i < c; i++) {
                uint64_t dd = dist[i];
                if (dd > worst) continue;
                int32_t id = N.ref[i];
                std::size_t pos;
                if (cnt < kk) {
                    pos = cnt++;
                } else {
                    if (dd == worst && id > rid[kk - 1]) continue;
                    pos = kk - 1;
                }
                while (pos > 0 && (rd[pos - 1] > dd || (rd[pos - 1] == dd && rid[pos - 1] > id))) {
                    rd[pos] = rd[pos - 1];
                    rid[pos] = rid[pos - 1];
                    pos--;
                }
                rd[pos] = dd;
                rid[pos] = id;
                if (cnt == kk) worst = rd[kk - 1];
            }
        } else {
            for (int i = 0; i < c; i++) {
                uint64_t dd = dist[i];
                if (dd > worst) continue;
                uint32_t ch = (uint32_t)N.ref[i];
                prefetch_node(&pool[ch]);
                heap.push_back({dd, ch});
                std::push_heap(heap.begin(), heap.end(), cmp);
            }
        }
    }
    for (std::size_t i = 0; i < cnt; i++) out[i] = rid[i];
    return cnt;
}

std::size_t RTree::height() const {
    if (size_ == 0) return 0;
    return (std::size_t)pool_[root_].level + 1;
}

std::size_t RTree::node_count() const {
    if (size_ == 0) return 0;
    std::vector<uint32_t> st{root_};
    std::size_t c = 0;
    while (!st.empty()) {
        uint32_t n = st.back();
        st.pop_back();
        c++;
        const Node& N = pool_[n];
        if (N.level > 0)
            for (int i = 0; i < N.count; i++) st.push_back((uint32_t)N.ref[i]);
    }
    return c;
}
