#' Print Method for Step-Stress Accelerated Degradation Fit
#'
#' Prints a concise summary of the fitted step-stress accelerated degradation model.
#'
#' @param x An object of class \code{"ssadfit"}.
#' @param ... Additional arguments passed to print.
#'
#' @return Invisibly returns the input object \code{x}.
#' @export
#' @examples
#' data(wiener_arrhenius)
#' fit <- ssad_fit(wiener_arrhenius, process = "wiener", model = "arrhenius", method = "mle")
#' print(fit)
print.ssadfit <- function(x, ...) {
  cat("\n=======================================================\n")
  cat("  Step-Stress Accelerated Degradation Model Fit\n")
  cat("=======================================================\n")
  cat("Process Model :", toupper(substr(x$process, 1, 1)), substring(x$process, 2), "Process\n")
  cat("Acceleration  :", toupper(substr(x$model, 1, 1)), substring(x$model, 2), "Model\n")
  cat("Method        :", toupper(x$method), "\n\n")
  
  cat("Estimated Parameters:\n")
  print(x$par)
  cat("\nLog-Likelihood:", format(x$loglik, digits = 6), "\n")
  cat("=======================================================\n\n")
  invisible(x)
}

#' Summary Method for Step-Stress Accelerated Degradation Fit
#'
#' Produces a detailed statistical summary of a fitted step-stress degradation model,
#' including parameter estimates, standard errors / MCMC quantiles, information criteria (AIC, BIC),
#' and MCMC convergence diagnostics (if fitted via MCMC).
#'
#' @param object An object of class \code{"ssadfit"}.
#' @param ... Additional arguments passed to summary.
#'
#' @return Invisibly returns the input object \code{object}.
#' @export
#' @examples
#' data(wiener_arrhenius)
#' fit <- ssad_fit(wiener_arrhenius, process = "wiener", model = "arrhenius", method = "mle")
#' summary(fit)
summary.ssadfit <- function(object, ...) {
  cat("\n=======================================================\n")
  cat("  Detailed Summary: SSADT Model Fit\n")
  cat("=======================================================\n")
  cat("Process       :", object$process, "\n")
  cat("Acceleration  :", object$model, "\n")
  cat("Method        :", object$method, "\n\n")
  
  k_params <- length(object$par)
  n_obs <- sum(sapply(object$units_data, nrow))
  aic_val <- 2 * k_params - 2 * object$loglik
  bic_val <- log(n_obs) * k_params - 2 * object$loglik
  
  cat("Model Selection Criteria:\n")
  cat("  Log-Likelihood :", format(object$loglik, digits = 6), "\n")
  cat("  AIC            :", format(aic_val, digits = 6), "\n")
  cat("  BIC            :", format(bic_val, digits = 6), "\n\n")
  
  if (object$method == "mle") {
    cat("Maximum Likelihood Estimates:\n")
    df_est <- data.frame(
      Estimate = object$par,
      Std.Error = object$se
    )
    print(df_est)
  } else { # MCMC
    cat("Bayesian MCMC Posterior Statistics:\n")
    df_est <- data.frame(
      Mean = object$par,
      Std.Dev = object$sd,
      MC.Error = object$sd / sqrt(nrow(object$chain)),
      object$quantiles
    )
    print(df_est)
    
    cat("\nMCMC Acceptance Rate:", format(object$acceptance_rate * 100, digits = 4), "%\n")
    cat("\nGeweke's MCMC Convergence Diagnostics:\n")
    g_diag <- geweke_diag(object$chain)
    print(g_diag)
  }
  cat("=======================================================\n\n")
  invisible(object)
}

#' Plot Diagnostics and Degradation Paths for SSADT Models
#'
#' Generates diagnostic plots for a fitted step-stress degradation model, including observed vs. fitted
#' degradation paths and MCMC trace/posterior density plots (if fitted via MCMC).
#'
#' @param x An object of class \code{"ssadfit"}.
#' @param ... Additional graphical parameters.
#'
#' @return Invisibly returns the input object \code{x}. Side effect: displays diagnostic plots.
#' @importFrom grDevices rainbow
#' @importFrom graphics par plot lines points abline
#' @importFrom utils head
#' @export
#' @examples
#' data(wiener_arrhenius)
#' fit <- ssad_fit(wiener_arrhenius, process = "wiener", model = "arrhenius", method = "mle")
#' plot(fit)
plot.ssadfit <- function(x, ...) {
  old_par <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(old_par))
  
  if (x$method == "mcmc" && !is.null(x$chain)) {
    graphics::par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
    
    # Subplot 1: Observed degradation paths
    units_data <- x$units_data
    t_max <- max(sapply(units_data, function(u) max(u$time)))
    x_max <- max(sapply(units_data, function(u) max(u$degradation)))
    
    graphics::plot(NULL, xlim = c(0, t_max), ylim = c(0, x_max * 1.1),
                   xlab = "Time (hours)", ylab = "Degradation Value",
                   main = paste("Degradation Paths (", x$process, ")", sep = ""))
    
    colors <- grDevices::rainbow(length(units_data))
    for (i in seq_along(units_data)) {
      u_df <- units_data[[i]]
      graphics::lines(u_df$time, u_df$degradation, col = colors[i], lwd = 2)
      graphics::points(u_df$time, u_df$degradation, col = colors[i], pch = 16, cex = 0.6)
    }
    for (om in x$thresholds) {
      graphics::abline(h = om, lty = 2, col = "gray40")
    }
    
    # Subplots 2-4: MCMC trace plots for parameters
    chain <- x$chain
    for (j in seq_len(ncol(chain))) {
      pname <- colnames(chain)[j]
      graphics::plot(chain[, j], type = "l", col = "blue",
                     xlab = "Iteration", ylab = pname,
                     main = paste("Trace Plot:", pname))
    }
  } else {
    graphics::par(mfrow = c(1, 1), mar = c(4, 4, 3, 1))
    units_data <- x$units_data
    t_max <- max(sapply(units_data, function(u) max(u$time)))
    x_max <- max(sapply(units_data, function(u) max(u$degradation)))
    
    graphics::plot(NULL, xlim = c(0, t_max), ylim = c(0, x_max * 1.1),
                   xlab = "Time (hours)", ylab = "Degradation Value",
                   main = paste("Step-Stress Accelerated Degradation Paths (", toupper(x$process), ")", sep = ""))
    
    colors <- grDevices::rainbow(length(units_data))
    for (i in seq_along(units_data)) {
      u_df <- units_data[[i]]
      graphics::lines(u_df$time, u_df$degradation, col = colors[i], lwd = 2)
      graphics::points(u_df$time, u_df$degradation, col = colors[i], pch = 16, cex = 0.7)
    }
    for (om in x$thresholds) {
      graphics::abline(h = om, lty = 2, col = "gray40")
    }
  }
  
  invisible(x)
}

#' Predict Lifetime Distribution and Reliability for SSADT Fit
#'
#' Predicts the reliability function R(t), cumulative failure distribution F(t), and MTTF at normal operating
#' stress conditions S0 based on a fitted \code{"ssadfit"} model.
#'
#' @param object An object of class \code{"ssadfit"}.
#' @param t Numeric vector of time points for reliability evaluation (default: \code{seq(100, 10000, by = 100)}).
#' @param S0 Normal use-stress level (default: 25).
#' @param omega_F Failure threshold for degradation (default: 200).
#' @param ... Additional prediction arguments.
#'
#' @return An object of class \code{"ssad_reliability"} containing time, reliability R(t), failure CDF F(t), and MTTF.
#' @export
#' @examples
#' data(wiener_arrhenius)
#' fit <- ssad_fit(wiener_arrhenius, process = "wiener", model = "arrhenius", method = "mle")
#' pred <- predict(fit, t = seq(100, 5000, by = 100), S0 = 25, omega_F = 200)
#' print(pred$mttf)
predict.ssadfit <- function(object, t = seq(100, 10000, by = 100), S0 = 25, omega_F = 200, ...) {
  rel <- ssad_reliability(
    t = t,
    process = object$process,
    model = object$model,
    params = object$par,
    S0 = S0,
    omega_F = omega_F
  )
  return(rel)
}
