# Internal numerical helpers for ssmodels

.ssmodels_clip_rho <- function(rho, eps = 1e-07) {
  pmin(pmax(rho, -1 + eps), 1 - eps)
}

.ssmodels_inv_mills <- function(eta) {
  exp(stats::dnorm(eta, log = TRUE) - stats::pnorm(eta, log.p = TRUE))
}

.ssmodels_safe_vcov <- function(hessian) {
  n <- if (is.null(hessian)) 0L else ncol(hessian)
  if (n == 0L) {
    return(matrix(NA_real_, nrow = 0L, ncol = 0L))
  }
  out <- tryCatch(solve(-hessian), error = function(e) NULL)
  if (is.null(out) || any(!is.finite(out))) {
    out <- tryCatch(MASS::ginv(-hessian), error = function(e) matrix(NA_real_, nrow = n, ncol = n))
  }
  out
}

.ssmodels_safe_se <- function(vcov) {
  se <- suppressWarnings(sqrt(diag(vcov)))
  se[!is.finite(se)] <- NA_real_
  se
}
