#' Malmquist (1950) Transformation for Type-II Censored Samples
#'
#' Converts an r-out-of-n Type-II right- or left-censored uniform sample into an independent
#' complete Uniform(0,1) sample of size r (Lin, Huang & Balakrishnan, 2008).
#'
#' @param u_cens Numeric vector of length r containing PIT-transformed order statistics.
#' @param n Total sample size (n >= length(u_cens)).
#' @param censoring Type of censoring: \code{"right"} or \code{"left"}.
#'
#' @return A list containing:
#' \item{W}{Sorted complete sample W_1:r < ... < W_r:r of size r.}
#' \item{V}{Vector of intermediate Beta-distributed random variables V_n, ..., V_\{n-r+1\}.}
#' @export
#'
#' @examples
#' u <- c(0.03, 0.06, 0.10, 0.11, 0.13)
#' transform_malmquist(u, n = 10, censoring = "right")
transform_malmquist <- function(u_cens, n, censoring = c("right", "left")) {
  censoring <- match.arg(censoring)
  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

  if (censoring == "left") {
    # Left-censoring reduction: u*_i:n = 1 - u_{n+1-i:n}
    u_cens <- 1 - u_cens[r:1]
  }

  u_cens <- pmin(pmax(u_cens, eps), 1 - eps)

  v <- numeric(r)
  v[1] <- 1 - u_cens[1]

  if (r > 1) {
    for (i in 1:(r - 1)) {
      denom <- 1 - u_cens[i]
      denom <- max(denom, eps)
      v[i + 1] <- (1 - u_cens[i + 1]) / denom
    }
  }

  v <- pmin(pmax(v, eps), 1 - eps)

  # W_i = V_{n-i+1}^{n-i+1} for i = 1, ..., r
  k_powers <- n:(n - r + 1)
  w <- v^k_powers

  w <- pmin(pmax(w, eps), 1 - eps)
  w_sorted <- sort(w)

  list(
    W = w_sorted,
    V = v
  )
}
