#' Approximate density of the untruncated DL tau-squared estimator
#'
#' `aedl_tau2_density()` evaluates the chi-square-mixture approximation used
#' internally for the untruncated DerSimonian-Laird estimator of the
#' between-study variance.
#'
#' @param vi Numeric vector of known within-study variances.
#' @param tau2 Non-negative value of the between-study variance.
#' @param nsim_chi Number of Monte Carlo samples for the chi-square mixture.
#' @param n_tau Number of grid intervals for the untruncated DL estimator.
#'
#' @return A list with grid values `x`, density values `y`, and auxiliary
#'   quantities used in the approximation.
#' @export
#'
#' @examples
#' vi <- c(0.04, 0.05, 0.03, 0.06)
#' d_tau <- aedl_tau2_density(
#'   vi = vi,
#'   tau2 = 0.01,
#'   nsim_chi = 500,
#'   n_tau = 50
#' )
#' str(d_tau[c("x", "y")])
aedl_tau2_density <- function(vi, tau2, nsim_chi = 100000, n_tau = 1000) {
  aedl_validate_density_inputs(
    vi = vi,
    tau2 = tau2,
    nsim_chi = nsim_chi,
    n_tau = n_tau
  )

  aedl_density_tau2dl(
    K = length(vi),
    sig2i = vi,
    tau2 = tau2,
    nsim_chi = nsim_chi,
    n_tau = n_tau
  )
}

#' Approximate density of the DL test statistic
#'
#' `aedl_stat_density()` evaluates the almost-exact density approximation of
#' the DerSimonian-Laird test statistic on a user-supplied grid.
#'
#' @param t_grid Numeric grid for the DerSimonian-Laird test statistic.
#' @param vi Numeric vector of known within-study variances.
#' @param tau2 Non-negative value of the between-study variance.
#' @param theta Mean parameter used in the conditional normal approximation.
#' @param nsim Number of Monte Carlo samples for conditional quantities.
#' @param nsim_chi Number of Monte Carlo samples for the chi-square mixture.
#' @param n_tau Number of grid intervals for the untruncated DL estimator.
#'
#' @return A list with grid values `x`, density values `y`, and auxiliary
#'   quantities used in the approximation.
#' @export
#'
#' @examples
#' vi <- c(0.04, 0.05, 0.03, 0.06)
#' d_stat <- aedl_stat_density(
#'   t_grid = seq(-4, 4, by = 0.5),
#'   vi = vi,
#'   tau2 = 0.01,
#'   nsim = 100,
#'   nsim_chi = 500,
#'   n_tau = 50
#' )
#' str(d_stat[c("x", "y")])
aedl_stat_density <- function(t_grid, vi, tau2, theta = 0, nsim = 10000,
                              nsim_chi = 100000, n_tau = 1000) {
  aedl_validate_density_inputs(
    vi = vi,
    tau2 = tau2,
    t_grid = t_grid,
    nsim = nsim,
    nsim_chi = nsim_chi,
    n_tau = n_tau
  )

  aedl_density_tdl(
    t_grid = t_grid,
    K = length(vi),
    sig2i = vi,
    tau2 = tau2,
    theta = theta,
    nsim = nsim,
    nsim_chi = nsim_chi,
    n_tau = n_tau
  )
}
