#pragma once

// Two-step parallel alias table construction [Hübschle-Schneider and Sanders 2019].
// Same table layout as alias.h: table[k].t is the split of column k, table[k].i its alias.
// Requires at least one item and a positive total weight.

#include "alias.h"
#include <thread>

struct ParallelAliasTable
{
    int n;
    std::vector<Alias> table;

    ParallelAliasTable(const std::vector<float>& values, int p) : n(values.size()), table(n)
    {
        // normalized weights (mean 1), light (t <= 1) and heavy (t > 1) items with prefix sums
        const double avg = std::accumulate(values.begin(), values.end(), 0.0) / n;
        std::vector<double> t(n), L{0}, H{0};
        std::vector<int> light, heavy;
        for(int k = 0; k < n; ++k)
        {
            t[k] = values[k] / avg;
            if(t[k] <= 1) { light.push_back(k); L.push_back(L.back() + t[k]); }
            else          { heavy.push_back(k); H.push_back(H.back() + t[k]); }
        }
        const int nl = light.size(), nh = heavy.size();

        // step 1: split the n columns into p parts. The first m = n' columns hold the first i light
        // and j = m - i heavy items, plus a spill s = m - (L[i] + H[j]) from heavy item j.
        // i is the first index with L[i] + H[m - i] <= m (n' * W/n with normalized weights),
        // found by binary search since L[i] + H[m - i] decreases with i.
        struct Split { int i, j; double s; };
        p = std::max(1, std::min(p, n));
        std::vector<Split> split(p + 1, {0, 0, 0.0});
        for(int k = 1; k <= p; ++k)
        {
            const int m = (long long)n * k / p;
            int lo = std::max(0, m - nh), hi = std::min(nl, m);
            while(lo < hi)
            {
                const int mid = (lo + hi) / 2;
                if(L[mid] + H[m - mid] <= m) hi = mid; else lo = mid + 1;
            }
            split[k] = {lo, m - lo, m - (L[lo] + H[m - lo])};
        }

        // step 2: run the sequential sweep on each part independently.
        // Part k packs lights [i_k, i_k+1) and heavies [j_k, j_k+1); its first heavy already gave
        // s_k to part k-1, and heavy j_k+1 (the spill) fills the remaining light columns.
        auto sweep = [&](int k)
        {
            int i = split[k].i, j = split[k].j;
            const int iend = split[k + 1].i, jend = split[k + 1].j;
            double w = (j < nh ? t[heavy[j]] : 0) - split[k].s;     // residual of heavy j
            while(i < iend || j < jend)
            {
                if(i < iend && (j == jend || w > 1))                 // pack a light column
                {
                    table[light[i]] = {float(t[light[i]]), j < nh ? heavy[j] : light[i]};
                    w -= 1 - t[light[i]];
                    ++i;
                }
                else                                                 // pack a heavy column
                {
                    const bool last = j + 1 == nh;
                    table[heavy[j]] = {float(w), last ? heavy[j] : heavy[j + 1]};
                    w = (last ? 0 : t[heavy[j + 1]]) - (1 - w);
                    ++j;
                }
            }
        };
        std::vector<std::thread> threads;
        for(int k = 0; k < p; ++k) threads.emplace_back(sweep, k);
        for(auto& thread : threads) thread.join();
    }

    int sample(const float u) const
    {
        const int id = n * u;
        const float u2 = n * u - id;
        return u2 < table[id].t ? id : table[id].i;
    }
};
