test_that("Closed-form W2_rn matches numerical integration across intervals", {
  u <- c(0.05, 0.12, 0.25, 0.40, 0.55)
  n <- 10
  r <- 5

  # Closed form
  stats_cf <- stat_edf_censored(u, n)
  w2_closed <- unname(stats_cf["W2_rn"])

  # Piecewise numerical integration per interval
  u_full <- c(0, u)
  w2_num_sum <- 0
  for (i in 0:(r - 1)) {
    i_n <- i / n
    u_a <- u_full[i + 1]
    u_b <- u_full[i + 2]
    val <- stats::integrate(function(uv) (i_n - uv)^2, lower = u_a, upper = u_b)$value
    w2_num_sum <- w2_num_sum + val
  }
  w2_num <- n * w2_num_sum

  expect_equal(w2_closed, w2_num, tolerance = 1e-6)
})

test_that("Closed-form A2_rn matches numerical integration across intervals", {
  u <- c(0.05, 0.12, 0.25, 0.40, 0.55)
  n <- 10
  r <- 5

  # Closed form
  stats_cf <- stat_edf_censored(u, n)
  a2_closed <- unname(stats_cf["A2_rn"])

  # Piecewise numerical integration per interval
  u_full <- c(0, u)
  a2_num_sum <- 0
  for (i in 0:(r - 1)) {
    i_n <- i / n
    u_a <- max(u_full[i + 1], 1e-7)
    u_b <- min(u_full[i + 2], 1 - 1e-7)
    val <- stats::integrate(function(uv) ((i_n - uv)^2) / (uv * (1 - uv)), lower = u_a, upper = u_b)$value
    a2_num_sum <- a2_num_sum + val
  }
  a2_num <- n * a2_num_sum

  expect_equal(a2_closed, a2_num, tolerance = 1e-3)
})
