#' Estimate the parameters of the regional distribution
#'
#' @param best_model
#' A 6-column `data.frame` as generated by `Best_model()`.
#' \itemize{
#'   \item Columns 1--5: `mu0`, `mu1`, `sigma0`,
#'         `sigma1`, `shape`.
#'   \item Column 6: `size` (sample size per site, used as weight).
#' }
#'
#' @returns
#' A one-row `data.frame` with the size-weighted regional parameters of a
#' time-varying generalized extreme value distribution.
#'
#' @export
#' @importFrom stats weighted.mean
#'
#' @examples
#' add.data <- Dataset_add(TmaxCPC_SP)
#' best.parms <- Best_model(add.data = add.data$add_data)
#' Reg_par(best_model = best.parms$atsite.models)

Reg_par <- function(best_model) {
  check_best_model_df(best_model)

  w <- best_model$size
  par_cols <- c("mu0", "mu1", "sigma0", "sigma1", "shape")

  # Replace non-finite parameter values with NA so they are excluded
  # from weighted.mean() along with genuinely missing fits.
  pars <- best_model[par_cols]
  pars[!is.finite(as.matrix(pars))] <- NA_real_

  wm <- vapply(
    pars,
    weighted.mean,
    w = w,
    na.rm = TRUE,
    FUN.VALUE = numeric(1)
  )

  names(wm) <- paste0("weighted_", par_cols)
  as.data.frame(as.list(wm))
}
