#' Add_RegProb
#'
#' @param quantiles
#' A numeric vector with no missing data containing extreme air temperatures.
#' @param regional_pars
#' A 5-column, 1-row `data.frame` or `matrix` as generated by `Reg_par()`.
#' @param site_temp
#' A non-empty numeric vector or 1-column matrix of site air temperature data.
#' @param n.year
#' A single integer giving the year index for which parameters are calculated.
#' Must be between 1 and `length(site_temp)`.
#'
#' @returns
#' A numeric matrix of cumulative probabilities (clamped to \[0.0001, 0.9999\])
#' associated with the input quantiles from the regional GEV distribution.
#'
#' @export
#' @importFrom extRemes pevd
#'
#'
#' @examples
#' quantiles <- c(37.8, 37.9, 38.0, 38.1, 38.2, 38.5, 39.0)
#' add.data <- Dataset_add(TmaxCPC_SP)
#' best.parms <- Best_model(add.data = add.data$add_data)
#' regional_pars <- Reg_par(best_model = best.parms$atsite.models)
#' Add_RegProb(
#'   quantiles     = quantiles,
#'   regional_pars = regional_pars,
#'   site_temp     = TmaxCPC_SP$Pixel_1,
#'   n.year        = 34
#' )
Add_RegProb <- function(quantiles, regional_pars, site_temp, n.year) {
  check_quantiles(quantiles) # defined in input_checks.R
  regional_pars <- check_reg_par(regional_pars) # reuses existing helper
  check_site_temp(site_temp) # defined in input_checks.R
  check_n.year(n.year, site_temp) # defined in input_checks.R

  site_mean <- mean(site_temp, na.rm = TRUE)
  loc <- regional_pars[1] + regional_pars[2] * n.year
  scale <- regional_pars[3] + regional_pars[4] * n.year
  shape <- regional_pars[5]

  if (scale <= 0) {
    stop("Calculated scale parameter must be positive.", call. = FALSE)
  }

  RegProb <- extRemes::pevd(
    quantiles - site_mean,
    loc = loc,
    scale = scale,
    shape = shape,
    type = "GEV"
  )

  # Clamp to valid probability range
  RegProb <- pmax(pmin(RegProb, 0.9999), 0.0001)

  as.matrix(RegProb)
}
