#include "hip/hip_runtime.h"
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#pragma once

#include <faiss/gpu/utils/Select.cuh>

namespace faiss {
namespace gpu {

template <
        typename K,
        typename IndexType,
        bool Dir,
        int NumWarpQ,
        int NumThreadQ,
        int ThreadsPerBlock>
__global__ void warpSelect(
        Tensor<K, 2, true> in,
        Tensor<K, 2, true> outK,
        Tensor<IndexType, 2, true> outV,
        K initK,
        IndexType initV,
        int k) {
    constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;

    WarpSelect<
            K,
            IndexType,
            Dir,
            Comparator<K>,
            NumWarpQ,
            NumThreadQ,
            ThreadsPerBlock>
            heap(initK, initV, k);

    int warpId = threadIdx.x / kWarpSize;
    int row = blockIdx.x * kNumWarps + warpId;

    if (row >= in.getSize(0)) {
        return;
    }

    int i = threadIdx.x % kWarpSize; // getLaneId();
    K* inStart = in[row][i].data();

    // Whole warps must participate in the selection
    int limit = utils::roundDown(in.getSize(1), kWarpSize);

    for (; i < limit; i += kWarpSize) {
        heap.add(*inStart, (IndexType)i);
        inStart += kWarpSize;
    }

    // Handle non-warp multiple remainder
    if (i < in.getSize(1)) {
        heap.addThreadQ(*inStart, (IndexType)i);
    }

    heap.reduce();
    heap.writeOut(outK[row].data(), outV[row].data(), k);

    //if(blockIdx.x < 2 && threadIdx.x < 2 )
    //printf("outK is %f, outV is %f\n", outK[row].data()[0], outV[row].data()[0]);
}

void runWarpSelect(
        Tensor<float, 2, true>& in,
        Tensor<float, 2, true>& outKeys,
        Tensor<int, 2, true>& outIndices,
        bool dir,
        int k,
        hipStream_t stream);

void runWarpSelect(
        Tensor<half, 2, true>& in,
        Tensor<half, 2, true>& outKeys,
        Tensor<int, 2, true>& outIndices,
        bool dir,
        int k,
        hipStream_t stream);

} // namespace gpu
} // namespace faiss
