// Chebyshev bounds propagator for Minimizing Partridge Packing, loaded by
// MiniZinc through :: blackbox_dll.
//
// Build (macOS):
//   c++ -std=c++17 -O3 -Wall -Wextra -dynamiclib \
//       -o libchebyshev_bounds.dylib chebyshev_bounds.cpp
//
// The propagator gets the bounds of position[1..P] ++ [max_pos], one
// [lb, ub] pair per variable, where position[p] is the Chebyshev cell number
// of part p's lower-left corner. Parts with lb == ub are placed. For every
// other part, the bounds are tightened past cells where the part would
// overlap a placed part or extend beyond the upper bound of max_pos.

#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <vector>

namespace {

// A cell of the board, with 0-based coordinates.
struct Cell {
  int x;
  int y;
};

// The cells covered by a square part, as half-open ranges [x0, x1) x [y0, y1).
struct Square {
  Square(Cell corner, int size)
      : x0(corner.x), y0(corner.y), x1(corner.x + size), y1(corner.y + size) {}

  bool overlaps(const Square& other) const {
    return x0 < other.x1 && other.x0 < x1 && y0 < other.y1 && other.y0 < y1;
  }

  int x0, y0, x1, y1;
};

struct Interval {
  std::int64_t lb;
  std::int64_t ub;

  bool fixed() const { return lb == ub; }
};

// Shell k holds the cells with max(x, y) = k and starts at k * k. Within a
// shell, the top strip (x < y) is numbered left to right, followed by the
// right strip (x >= y) bottom to top.
std::int64_t cell_number(Cell cell) {
  const std::int64_t k = std::max(cell.x, cell.y);
  return cell.x < cell.y ? k * k + cell.x : k * k + k + cell.y;
}

Cell cell_at(std::int64_t number) {
  auto k = static_cast<std::int64_t>(std::sqrt(static_cast<double>(number)));
  while ((k + 1) * (k + 1) <= number) ++k;
  while (k * k > number) --k;
  const std::int64_t offset = number - k * k;
  if (offset < k) return {static_cast<int>(offset), static_cast<int>(k)};
  return {static_cast<int>(k), static_cast<int>(offset - k)};
}

// The instance size n with n (n + 1) / 2 parts, or 0 if there is none.
int instance_size(std::int64_t parts) {
  int n = 1;
  while (std::int64_t{n} * (n + 1) / 2 < parts) ++n;
  return std::int64_t{n} * (n + 1) / 2 == parts ? n : 0;
}

// Part sizes and cell coordinates for one instance size.
struct Instance {
  explicit Instance(int n)
      : parts(n * (n + 1) / 2), board_side(n * (n + 1)) {
    for (int size = n; size >= 1; --size) sizes.insert(sizes.end(), size, size);
    cells.reserve(static_cast<std::size_t>(board_side) * board_side);
    for (std::int64_t number = 0; number < std::int64_t{board_side} * board_side; ++number) {
      cells.push_back(cell_at(number));
    }
  }

  // The number of parts, which is also the side of a perfect tiling.
  int parts;
  // The board in the model is twice the side of a perfect tiling.
  int board_side;
  // Largest first, matching the model's sizes.
  std::vector<int> sizes;
  // The cell for each cell number, so that the hot loops avoid sqrt.
  std::vector<Cell> cells;
};

constexpr int max_instance_size = 31;

// Instances are built once and shared by every propagator call, including
// calls from parallel search threads.
const Instance* instance_for(std::int64_t parts) {
  const int n = instance_size(parts);
  if (n < 1 || n > max_instance_size) return nullptr;
  static std::array<std::once_flag, max_instance_size + 1> built;
  static std::array<std::unique_ptr<const Instance>, max_instance_size + 1> instances;
  std::call_once(built[n], [n] { instances[n] = std::make_unique<const Instance>(n); });
  return instances[n].get();
}

// Tightens the position bounds of the unplaced parts, given the upper bound
// of max_pos. Returns false when no packing is possible.
bool propagate(const Instance& instance, std::vector<Interval>& positions,
               std::int64_t max_side) {
  const int side = static_cast<int>(std::min<std::int64_t>(max_side, instance.board_side));
  if (side < instance.parts) return false;

  std::vector<Square> placed;
  placed.reserve(positions.size());
  const auto overlaps_placed = [&placed](const Square& square) {
    return std::any_of(placed.begin(), placed.end(),
                       [&square](const Square& other) { return square.overlaps(other); });
  };

  // Keep every part inside the side, and collect the placed parts.
  for (std::size_t p = 0; p < positions.size(); ++p) {
    Interval& position = positions[p];
    const int size = instance.sizes[p];
    const int last = side - size;
    if (last < 0) return false;
    position.lb = std::max<std::int64_t>(position.lb, 0);
    position.ub = std::min(position.ub, cell_number({last, last}));
    if (position.lb > position.ub) return false;

    if (position.fixed()) {
      const Square square(instance.cells[position.lb], size);
      if (square.x1 > side || square.y1 > side || overlaps_placed(square)) return false;
      placed.push_back(square);
    }
  }
  if (placed.empty()) return true;

  // Move the bounds of every unplaced part past the cells where it cannot go.
  for (std::size_t p = 0; p < positions.size(); ++p) {
    Interval& position = positions[p];
    if (position.fixed()) continue;
    const int size = instance.sizes[p];
    const int last = side - size;
    const auto fits = [&](std::int64_t number) {
      const Cell cell = instance.cells[number];
      return cell.x <= last && cell.y <= last && !overlaps_placed(Square(cell, size));
    };

    while (position.lb <= position.ub && !fits(position.lb)) ++position.lb;
    if (position.lb > position.ub) return false;
    while (position.ub > position.lb && !fits(position.ub)) --position.ub;
  }
  return true;
}

}  // namespace

#if defined(_WIN32)
#define FZN_BLACKBOX_EXPORT __declspec(dllexport)
#define FZN_BLACKBOX_CALL __stdcall
#else
#define FZN_BLACKBOX_EXPORT __attribute__((visibility("default")))
#define FZN_BLACKBOX_CALL
#endif

// The entry point MiniZinc's blackbox_dll calls. Integer variables arrive as
// lb, ub pairs, and the result is written in the same layout. An empty
// interval for the first variable signals failure. The propagator has no
// float variables.
extern "C" FZN_BLACKBOX_EXPORT void FZN_BLACKBOX_CALL fzn_blackbox(
    void* /*instance*/,
    const std::int64_t* int_in, std::size_t int_in_size,
    const double* /*float_in*/, std::size_t /*float_in_size*/,
    std::int64_t* int_out, std::size_t int_out_size,
    double* /*float_out*/, std::size_t /*float_out_size*/) noexcept {
  std::copy(int_in, int_in + int_in_size, int_out);
  if (int_in_size < 4 || int_out_size < int_in_size) return;

  // No exception may cross the C interface. Without an answer, the bounds
  // stay as they were, which is always sound.
  try {
    const std::size_t parts = int_in_size / 2 - 1;
    const Instance* instance = instance_for(static_cast<std::int64_t>(parts));
    if (instance == nullptr) return;

    std::vector<Interval> positions(parts);
    for (std::size_t p = 0; p < parts; ++p) positions[p] = {int_in[2 * p], int_in[2 * p + 1]};

    if (!propagate(*instance, positions, int_in[2 * parts + 1])) {
      int_out[0] = 1;
      int_out[1] = 0;
      return;
    }
    for (std::size_t p = 0; p < parts; ++p) {
      int_out[2 * p] = positions[p].lb;
      int_out[2 * p + 1] = positions[p].ub;
    }
  } catch (...) {
    std::copy(int_in, int_in + int_in_size, int_out);
  }
}
