# ============================================================
# Internal helper: random edge removal (sparsification).
# ============================================================


#' Randomly remove edges from an undirected network
#'
#' Each edge in the undirected network is independently retained with
#' probability \code{p} (equivalently, removed with probability
#' \code{1 - p}).  The operation generates a symmetric Bernoulli mask on the
#' upper triangle and mirrors it, preserving the symmetry of the adjacency
#' matrix.
#'
#' @param A A square symmetric binary matrix (\strong{dense}).
#' @param p Numeric in \eqn{[0, 1]}; the probability of retaining each edge.
#'
#' @return A dense integer matrix of the same dimensions as \code{A}.
#'
#' @importFrom stats rbinom
#' @keywords internal
sparsify_graph <- function(A, p) {

  if (p >= 1) return(A)
  if (p <= 0) return(matrix(0L, nrow(A), ncol(A)))

  n       <- nrow(A)
  n_upper <- n * (n - 1L) / 2L

  mask              <- matrix(0L, n, n)
  mask[upper.tri(mask)] <- stats::rbinom(n_upper, 1L, p)
  mask              <- mask + t(mask)

  A * mask
}
