/****************************************************************************
 * Copyright (c) 2025, ArborX authors                                       *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the ArborX library. ArborX is                       *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include "ArborXTest_StdVectorToKokkosView.hpp"
#include "ArborX_EnableDeviceTypes.hpp"
#include "ArborX_EnableViewComparison.hpp"
#include <ArborX_DBSCANVerification.hpp>
#include <ArborX_DistributedDBSCAN.hpp>

#include "BoostTest_CUDA_clang_workarounds.hpp"
#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <map>
#include <numeric>
#include <random>
#include <vector>

#include <mpi.h>

namespace tt = boost::test_tools;

bool operator==(ArborX::Details::MergePair const &a,
                ArborX::Details::MergePair const &b)
{
  return a.from == b.from && a.to == b.to;
}

BOOST_AUTO_TEST_SUITE(DistributedDBSCAN)

BOOST_AUTO_TEST_CASE_TEMPLATE(sort_and_filter_merge_pairs, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  using ArborX::Details::MergePair;
  using ArborXTest::toView;

  typename DeviceType::execution_space space;

  int comm_rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank);

  // The original edges connect every label to 0. Filtering 8's two outgoing
  // edges reinserts 7 -> 6, which collides with the existing 7 -> 5. A single
  // filter pass leaves two edges from 7, and relabel() follows only one.
  auto merge_pairs = toView<DeviceType, MergePair>(
      {{8, 6}, {8, 7}, {7, 5}, {6, 4}, {5, 3}, {4, 2}, {3, 1}, {2, 0}});
  ArborX::Details::sortAndFilterMergePairs(space, merge_pairs);
  std::vector<MergePair> merge_pairs_ref = {{1, 0}, {2, 0}, {3, 0}, {4, 0},
                                            {5, 0}, {6, 0}, {7, 0}, {8, 0}};
  if (comm_rank == 0)
  {
    auto merge_pairs_host =
        Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace{}, merge_pairs);
    BOOST_TEST(merge_pairs_host == merge_pairs_ref, tt::per_element());
  }

  auto labels = toView<DeviceType, long long>({0, 1, 2, 3, 4, 5, 6, 7, 8});
  ArborX::Details::relabel(space, merge_pairs, labels);
  std::vector<long long> labels_ref = {0, 0, 0, 0, 0, 0, 0, 0, 0};
  if (comm_rank == 0)
  {
    auto labels_host =
        Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace{}, labels);
    BOOST_TEST(labels_host == labels_ref, tt::per_element());
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(nonmonotonic_connected_path, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  using MemorySpace = typename DeviceType::memory_space;
  using Point = ArborX::Point<2, float>;
  using ArborXTest::toView;
  typename DeviceType::execution_space space;

  int comm_rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank);
  int comm_size;
  MPI_Comm_size(MPI_COMM_WORLD, &comm_size);

  // The connected path has a nonmonotone (pyramid) point order.
  // For comm_size = 9: path = {0, 2, 4, 6, 8, 7, 5, 3, 1}
  std::vector<int> path(comm_size);
  for (int i = 0; i < comm_size; ++i)
    path[i] = (i <= (comm_size - 1) / 2 ? 2 * i : 2 * (comm_size - i) - 1);

  // Each path point is on a different rank
  std::vector<Point> points_ref(comm_size);
  for (int i = 0; i < comm_size; ++i)
    points_ref[path[i]] = {{(float)i, 0}};

  constexpr float eps = 1.1f;
  constexpr int minpts = 2;
  auto points = toView<DeviceType, Point>({points_ref[comm_rank]});

  Kokkos::View<long long *, MemorySpace> labels("distributed_labels", 0);
  ArborX::Experimental::dbscan(MPI_COMM_WORLD, space, points, eps, minpts,
                               labels);
  BOOST_TEST(ArborX::Details::verifyDBSCAN(MPI_COMM_WORLD, space, points, eps,
                                           minpts, labels, true /*verbose*/));

  std::vector<long long> labels_ref = {0};
  auto labels_host =
      Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace{}, labels);
  BOOST_TEST(labels_host == labels_ref, tt::per_element());
}

BOOST_AUTO_TEST_SUITE_END()
