#' Density approximation for the untruncated DL tau-squared estimator
#'
#' Internal helper. This file will contain the chi-square-mixture approximation
#' currently represented by `pdf_tau2dl_fast()` in the prototype code.
#'
#' @keywords internal
aedl_density_tau2dl <- function(K, sig2i, tau2, nsim_chi = 100000,
                                n_tau = 1000) {
  s1 <- sum(1 / sig2i)
  s2 <- sum(1 / sig2i^2)
  denom <- s1 - s2 / s1

  V <- matrix(0, nrow = K, ncol = K)

  for (i in seq_len(K)) {
    for (j in seq_len(K)) {
      V[i, j] <-
        -1 / s1 +
        (s2 / s1^2 - (1 / sig2i[i] + 1 / sig2i[j]) / s1) * tau2
    }

    V[i, i] <-
      (sig2i[i] - 1 / s1) +
      (1 + s2 / s1^2 - 2 / (sig2i[i] * s1)) * tau2
  }

  W <- diag(1 / sig2i, nrow = K, ncol = K)
  lambda <- Re(eigen(V %*% W, only.values = TRUE)$values)

  chi_sim <- matrix(
    stats::rchisq(nsim_chi * K, df = 1),
    nrow = nsim_chi,
    ncol = K
  )

  Q_chis <- as.vector(chi_sim %*% lambda)
  Fq <- stats::ecdf(Q_chis)

  qmin <- min(Q_chis)
  qmax <- max(Q_chis)
  h <- (qmax - qmin) / n_tau

  q_grid <- (0:n_tau) * h
  fq <- (Fq(q_grid + h) - Fq(q_grid)) / h

  x_tau2 <- (q_grid - (K - 1)) / denom
  f_tau2 <- denom * fq

  list(
    x = x_tau2,
    y = f_tau2,
    q = q_grid,
    fq = fq,
    Fq = Fq
  )
}
