#' Calibrate Dynamic SDE and Jump Parameters
#'
#' Estimates mean-reversion speed, unconditional volatility, and jump characteristics.
#'
#' @param residuals Numeric vector of detrended temperature residuals X(t).
#' @param n_years Numeric scalar representing total observation period in years.
#' @param threshold_sigma Threshold multiplier for jump identification (default: 2.5).
#' @return A named list of calibrated stochastic differential parameters.
#' @examples
#' set.seed(123)
#' res <- stats::rnorm(730, sd = 2)
#' calib <- calibrate_mrjd(res, n_years = 2)
#' print(calib$kappa)
#' @export
calibrate_mrjd <- function(residuals, n_years, threshold_sigma = 2.5) {
  res_current <- residuals[1:(length(residuals) - 1)]
  res_diff    <- diff(residuals)
  
  ar_fit <- stats::lm(res_diff ~ res_current)
  kappa  <- -stats::coef(ar_fit)[2]
  sigma  <- stats::sd(residuals)
  
  anomaly_cutoff <- threshold_sigma * sigma
  jumps <- residuals[abs(residuals) > anomaly_cutoff]
  
  lambda_annual <- length(jumps) / n_years
  mu_j    <- if(length(jumps) > 0) mean(jumps) else 0
  sigma_j <- if(length(jumps) > 1) stats::sd(jumps) else 0
  
  list(
    kappa = as.numeric(kappa),
    sigma = sigma,
    lambda = lambda_annual,
    mu_jump = mu_j,
    sigma_jump = sigma_j,
    jump_count = length(jumps)
  )
}
