#' Compute Standard Errors, MSE, and Coverage Probabilities for Interval-Censored Data
#'
#' Computes standard errors, mean squared errors, and coverage probabilities for
#' distribution parameters and process capability indices using bootstrap results.
#'
#' @param fit A \code{gpcifit_censor} object returned by \code{\link{capability_censor}}.
#' @param true_params Named list of true parameter values (if known, for simulation studies).
#' @param true_indices Named vector of true index values (if known, for simulation studies).
#' @param B Number of bootstrap replicates for SE computation (default is 1000).
#' @param alpha Vector of significance levels for coverage probability (default is \code{c(0.10, 0.05, 0.01)}).
#' @return A list of class \code{"gpci_diagnostics_censor"} containing standard errors, MSE, and coverage probabilities.
#' @export
#' @examples
#' \dontrun{
#' dist_norm <- dist_normal()
#' left <- c(9.5, 10.2, 8.8, 11.1, 9.9)
#' right <- c(10.5, 11.2, 9.8, 12.1, 10.9)
#' fit <- capability_censor(left, right, dist_norm, USL = 13, LSL = 7)
#' diagnostics <- compute_diagnostics_censor(fit, B = 500)
#' print(diagnostics)
#' }
compute_diagnostics_censor <- function(fit, true_params = NULL, true_indices = NULL, 
                                        B = 1000, alpha = c(0.10, 0.05, 0.01)) {
  if (!inherits(fit, "gpcifit_censor")) {
    stop("fit must be of class 'gpcifit_censor'")
  }
  
  boot_res <- boot_ci_censor(fit, B = B, alpha = alpha, method = "percentile")
  
  indices <- fit$indices
  boot_t <- boot_res$boot_out$t
  
  se_indices <- sapply(seq_along(indices), function(i) {
    reps <- boot_t[, i]
    reps <- reps[is.finite(reps)]
    if (length(reps) > 0) {
      val <- stats::sd(reps, na.rm = TRUE)
      if (is.na(val) || !is.finite(val)) val <- 0
      val
    } else {
      0
    }
  })
  names(se_indices) <- indices
  
  mse_indices <- NULL
  if (!is.null(true_indices)) {
    mse_indices <- sapply(indices, function(idx) {
      if (idx %in% names(true_indices)) {
        est <- fit$estimates[idx]
        true_val <- true_indices[idx]
        val <- (est - true_val)^2
        if (is.na(val) || !is.finite(val)) val <- 0
        val
      } else {
        0
      }
    })
  }
  
  coverage_indices <- list()
  for (a in alpha) {
    coverage <- sapply(seq_along(indices), function(i) {
      reps <- boot_t[, i]
      reps <- reps[is.finite(reps)]
      if (length(reps) > 0 && !is.null(true_indices) && indices[i] %in% names(true_indices)) {
        ci_lower <- stats::quantile(reps, probs = a / 2, na.rm = TRUE)
        ci_upper <- stats::quantile(reps, probs = 1 - a / 2, na.rm = TRUE)
        true_val <- true_indices[indices[i]]
        as.numeric(true_val >= ci_lower && true_val <= ci_upper)
      } else {
        0
      }
    })
    names(coverage) <- indices
    coverage_indices[[paste0("alpha_", a)]] <- coverage
  }
  
  param_names <- names(fit$distribution$params)
  se_params <- sapply(param_names, function(pname) {
    n <- length(fit$data_left)
    jack_est <- numeric(n)
    for (i in 1:n) {
      left_j <- fit$data_left[-i]
      right_j <- fit$data_right[-i]
      fit_j <- tryCatch({
        fit_distribution_censor(left_j, right_j, fit$distribution)
      }, error = function(e) NULL)
      
      if (!is.null(fit_j)) {
        jack_est[i] <- fit_j$params[[pname]]
      } else {
        jack_est[i] <- fit$distribution$params[[pname]]
      }
    }
    jack_est <- jack_est[is.finite(jack_est)]
    if (length(jack_est) > 0) {
      val <- sqrt((n - 1) / n * stats::var(jack_est))
      if (is.na(val) || !is.finite(val)) val <- 0
      val
    } else {
      0
    }
  })
  
  mse_params <- NULL
  if (!is.null(true_params)) {
    mse_params <- sapply(param_names, function(pname) {
      if (pname %in% names(true_params)) {
        est <- fit$distribution$params[[pname]]
        true_val <- true_params[[pname]]
        val <- (est - true_val)^2
        if (is.na(val) || !is.finite(val)) val <- 0
        val
      } else {
        0
      }
    })
  }
  
  coverage_params <- list()
  if (!is.null(true_params)) {
    for (a in alpha) {
      coverage <- sapply(param_names, function(pname) {
        if (pname %in% names(true_params)) {
          est <- fit$distribution$params[[pname]]
          se <- se_params[pname]
          if (is.finite(se) && se > 0) {
            ci_lower <- est - stats::qnorm(1 - a / 2) * se
            ci_upper <- est + stats::qnorm(1 - a / 2) * se
            true_val <- true_params[[pname]]
            as.numeric(true_val >= ci_lower && true_val <= ci_upper)
          } else {
            0
          }
        } else {
          0
        }
      })
      names(coverage) <- param_names
      coverage_params[[paste0("alpha_", a)]] <- coverage
    }
  }
  
  structure(
    list(
      se_indices = se_indices,
      mse_indices = mse_indices,
      coverage_indices = coverage_indices,
      se_params = se_params,
      mse_params = mse_params,
      coverage_params = coverage_params,
      alpha_levels = alpha,
      bootstrap_replicates = B
    ),
    class = "gpci_diagnostics_censor"
  )
}

#' @rdname compute_diagnostics_censor
#' @export
gpci_diagnostics_censor <- compute_diagnostics_censor

#' Print Method for gpci_diagnostics_censor
#'
#' @param x An object of class \code{gpci_diagnostics_censor}.
#' @param ... Additional print arguments.
#' @export
print.gpci_diagnostics_censor <- function(x, ...) {
  cat("--- Diagnostics for Interval-Censored Data ---\n")
  cat("Bootstrap Replicates:", x$bootstrap_replicates, "\n\n")
  
  cat("Standard Errors for Parameters:\n")
  print(round(x$se_params, 6))
  
  if (!is.null(x$mse_params)) {
    cat("\nMean Squared Errors for Parameters:\n")
    print(round(x$mse_params, 6))
  }
  
  cat("\nStandard Errors for Capability Indices:\n")
  print(round(x$se_indices, 6))
  
  if (!is.null(x$mse_indices)) {
    cat("\nMean Squared Errors for Capability Indices:\n")
    print(round(x$mse_indices, 6))
  }
  
  if (length(x$coverage_indices) > 0) {
    cat("\nCoverage Probabilities for Capability Indices:\n")
    for (a_name in names(x$coverage_indices)) {
      cat("\nAlpha level:", a_name, "\n")
      print(round(x$coverage_indices[[a_name]], 4))
    }
  }
  
  if (length(x$coverage_params) > 0) {
    cat("\nCoverage Probabilities for Parameters:\n")
    for (a_name in names(x$coverage_params)) {
      cat("\nAlpha level:", a_name, "\n")
      print(round(x$coverage_params[[a_name]], 4))
    }
  }
  
  invisible(x)
}

#' Summary Method for gpci_diagnostics_censor
#'
#' @param object An object of class \code{gpci_diagnostics_censor}.
#' @param ... Additional arguments.
#' @export
summary.gpci_diagnostics_censor <- function(object, ...) {
  print(object, ...)
  invisible(object)
}
