#' Compute EDF Statistics for Type-II Censored Samples
#'
#' Computes the nine EDF test statistics described in Lin, Huang & Balakrishnan (2008).
#'
#' @param u_cens Numeric vector of order statistics u_1:n < ... < u_r:n in (0, 1).
#' @param n Total sample size (n >= length(u_cens)).
#' @param u_ms Optional pre-computed Michael & Schucany transformed sample.
#' @param u_malmquist Optional pre-computed Malmquist transformed sample.
#'
#' @return A named numeric vector of 9 statistics: \code{D_rn}, \code{G_rn}, \code{T_rn},
#' \code{W2_star_rn}, \code{W2_rn}, \code{A2_rn}, \code{U2_rn}, \code{TA2_r}, and \code{star_TA2_r}.
#' @export
#'
#' @examples
#' u <- c(0.03, 0.06, 0.10, 0.11, 0.13)
#' stat_edf_censored(u, n = 10)
stat_edf_censored <- function(u_cens, n, u_ms = NULL, u_malmquist = NULL) {
  if (!is.numeric(u_cens) || length(u_cens) == 0) {
    stop("`u_cens` must be a non-empty numeric vector.")
  }
  if (is.unsorted(u_cens)) {
    stop("`u_cens` must be sorted ascending.")
  }
  r <- length(u_cens)
  if (!is.numeric(n) || length(n) != 1 || n < r) {
    stop("`n` must be an integer >= length(u_cens).")
  }

  eps <- .Machine$double.eps^0.5
  u_cens <- pmin(pmax(u_cens, eps), 1 - eps)

  i_seq <- 1:r

  # 1. Modified Kolmogorov-Smirnov (D_{r,n})
  term1 <- abs(i_seq / n - u_cens)
  term2 <- abs((i_seq - 1) / n - u_cens)
  D_rn <- max(max(term1), max(term2))

  # 2. Squared-spacings statistic (G_{r,n})
  u_prev <- c(0, u_cens[1:(r - 1)])
  sum_sq_spacings <- sum((u_cens - u_prev)^2)
  u_r <- u_cens[r]
  term_end <- ((1 - u_r)^2) / (n - r + 1)
  G_rn <- (n + 1) * (n + 2) * (sum_sq_spacings + term_end) - (n + 2)

  # 3. Modified correlation statistic (T_{r,n})
  if (r == 1) {
    T_rn <- NA_real_
  } else {
    r_cor <- stats::cor(u_cens, i_seq)
    T_rn <- 1 - r_cor^2
  }

  # 4. Modified Cramér-von Mises star form (*W²_{r,n})
  W2_star_rn <- 1 / (12 * n) + sum((u_cens - (2 * i_seq - 1) / (2 * n))^2)

  # 5. Modified Cramér-von Mises integral form (W²_{r,n})
  u_full <- c(0, u_cens)
  i_idx <- 0:(r - 1)
  term_w2 <- (i_idx / n - u_full[i_idx + 1])^3 - (i_idx / n - u_full[i_idx + 2])^3
  W2_rn <- (n / 3) * sum(term_w2)

  # 6. Modified Anderson-Darling integral form (A²_{r,n})
  term_ad <- numeric(r)
  # i = 0 special case: (0/n)^2 * ln(...) is 0
  term_ad[1] <- - (1)^2 * (log(1 - u_full[2]) - log(1 - 0)) - (u_full[2] - 0)
  if (r > 1) {
    for (idx in 2:r) {
      i_val <- idx - 1
      in_ratio <- i_val / n
      u_curr <- u_full[idx]
      u_next <- u_full[idx + 1]
      term_ad[idx] <- (in_ratio^2) * (log(u_next) - log(u_curr)) -
        ((1 - in_ratio)^2) * (log(1 - u_next) - log(1 - u_curr)) -
        (u_next - u_curr)
    }
  }
  A2_rn <- n * sum(term_ad)

  # 7. Modified Watson statistic (U²_{r,n})
  sum_u <- sum(u_cens)
  bracket <- (r / n) - (u_r / 2) - (sum_u / (n * u_r))
  U2_rn <- W2_rn - n * u_r * (bracket^2)

  # Helper for complete AD statistic
  calc_ad_complete <- function(u_comp) {
    u_comp <- sort(pmin(pmax(u_comp, eps), 1 - eps))
    -r - (1 / r) * sum((2 * i_seq - 1) * log(u_comp) + (2 * r + 1 - 2 * i_seq) * log(1 - u_comp))
  }

  # 8. AD on Transformation A (Michael & Schucany)
  if (is.null(u_ms)) {
    u_ms <- transform_ms(u_cens, n)
  }
  TA2_r <- calc_ad_complete(u_ms)

  # 9. AD on Transformation B (Malmquist)
  if (is.null(u_malmquist)) {
    u_malmquist <- transform_malmquist(u_cens, n, censoring = "right")$W
  }
  star_TA2_r <- calc_ad_complete(u_malmquist)

  c(
    D_rn = D_rn,
    G_rn = G_rn,
    T_rn = T_rn,
    W2_star_rn = W2_star_rn,
    W2_rn = W2_rn,
    A2_rn = A2_rn,
    U2_rn = U2_rn,
    TA2_r = TA2_r,
    star_TA2_r = star_TA2_r
  )
}

#' Compute Direct Censored EDF Statistics (Pettitt & Stephens, 1976)
#'
#' Computes the untransformed direct censored Cramér-von Mises and Anderson-Darling statistics.
#'
#' @param u_cens Numeric vector of order statistics u_1:n < ... < u_r:n in (0, 1).
#' @param n Total sample size (n >= length(u_cens)).
#'
#' @return Named numeric vector containing \code{W2_2_rn} and \code{A2_2_rn}.
#' @export
#'
#' @examples
#' u <- c(0.03, 0.06, 0.10, 0.11, 0.13)
#' stat_direct_censored(u, n = 10)
stat_direct_censored <- function(u_cens, n) {
  if (!is.numeric(u_cens) || length(u_cens) == 0) {
    stop("`u_cens` must be a non-empty numeric vector.")
  }
  if (is.unsorted(u_cens)) {
    stop("`u_cens` must be sorted ascending.")
  }
  r <- length(u_cens)
  if (!is.numeric(n) || length(n) != 1 || n < r) {
    stop("`n` must be an integer >= length(u_cens).")
  }

  eps <- .Machine$double.eps^0.5
  v <- pmin(pmax(u_cens, eps), 1 - eps)
  v_r <- v[r]
  i_seq <- 1:r

  W2_2_rn <- sum((v - (2 * i_seq - 1) / (2 * n))^2) + (r / (12 * n^2)) + (n / 3) * ((v_r - r / n)^3)

  t1 <- -(1 / n) * sum((2 * i_seq - 1) * (log(v) - log(1 - v)))
  t2 <- -2 * sum(log(1 - v))
  t3 <- -(1 / n) * (((r - n)^2) * log(1 - v_r) - (r^2) * log(v_r) + (n^2) * v_r)

  A2_2_rn <- t1 + t2 + t3

  c(W2_2_rn = W2_2_rn, A2_2_rn = A2_2_rn)
}
