.status_symbol <- function(status) {
  switch(status,
    PASS = "[PASS]", PASSED = "[PASS]",
    WARN = "[WARN]", REVIEW = "[REVIEW]", WARNING = "[WARN]",
    FAIL = "[FAIL]", FAILED = "[FAIL]", ERROR = "[ERROR]",
    `NOT EVALUATED` = "[N/A]", paste0("[", status, "]")
  )
}

.domain_label <- function(x) {
  switch(x,
    computational_integrity = "Computational integrity",
    numerical_stability = "Numerical stability",
    design_adequacy = "Design adequacy",
    assumption_screening = "Assumption screening",
    influence_stability = "Influence stability",
    other = "Other checks",
    x
  )
}

#' @export
print.statwitness_audit <- function(x, ..., details = FALSE) {
  cat("STATWITNESS VALIDATION CERTIFICATE\n")
  cat(strrep("=", 60), "\n", sep = "")
  cat("Model type:   ", x$model_type, "\n", sep = "")
  if (!is.null(x$formula)) cat("Formula:      ", paste(deparse(x$formula), collapse = " "), "\n", sep = "")
  cat("Focus:        ", x$primary$label, if (x$focus_inferred) " (inferred)" else "", "\n", sep = "")
  cat("Observations: ", x$primary$n, "\n", sep = "")
  if (!is.null(x$audit_level)) cat("Audit level:  ", x$audit_level, "\n", sep = "")

  cat("\nPRIMARY RESULT\n")
  cat(strrep("-", 60), "\n", sep = "")
  if (identical(x$primary$kind, "term")) {
    cat("Omnibus term: ", x$primary$label, "\n", sep = "")
    cat("Test method:  ", x$primary$method, "\n", sep = "")
    cat("Statistic:    ", .format_num(x$primary$statistic), "\n", sep = "")
    if (length(x$primary$df) == 2L) {
      cat("Degrees df:   ", paste(.format_num(x$primary$df), collapse = ", "), "\n", sep = "")
    } else if (length(x$primary$df) == 1L && !is.na(x$primary$df)) {
      cat("Degrees df:   ", .format_num(x$primary$df), "\n", sep = "")
    }
    if (!is.na(x$primary$estimate)) {
      label <- x$primary$effect_size_label %||% "Effect-size estimate"
      cat(label, ": ", .format_num(x$primary$estimate), "\n", sep = "")
    }
    cat("p-value:      ", format.pval(x$primary$p_value, digits = 4, eps = 0.0001), "\n", sep = "")
  } else {
    cat("Estimate:     ", .format_num(x$primary$estimate), "\n", sep = "")
    cat(round(100 * x$primary$conf_level), "% CI:      [", .format_num(x$primary$lower), ", ", .format_num(x$primary$upper), "]\n", sep = "")
    cat("p-value:      ", format.pval(x$primary$p_value, digits = 4, eps = 0.0001), "\n", sep = "")
    if (!is.null(x$primary$transformed)) {
      tr <- x$primary$transformed
      cat(tr$label, ": ", .format_num(tr$estimate), " [", .format_num(tr$lower), ", ", .format_num(tr$upper), "]\n", sep = "")
    }
  }

  domains <- x$domains %||% .domain_summary(x$tests)
  cat("\nAUDIT DOMAINS\n")
  cat(strrep("-", 60), "\n", sep = "")
  for (i in seq_len(nrow(domains))) {
    cat(.status_symbol(domains$status[[i]]), " ", .domain_label(domains$domain[[i]]),
        " - ", domains$passed[[i]], " passed, ", domains$review[[i]], " review item(s)\n", sep = "")
  }

  show <- if (isTRUE(details)) rep(TRUE, nrow(x$tests)) else x$tests$status != "PASS"
  if (any(show)) {
    cat("\n", if (isTRUE(details)) "ALL REGISTERED TESTS" else "FINDINGS REQUIRING REVIEW", "\n", sep = "")
    cat(strrep("-", 60), "\n", sep = "")
    idx <- which(show)
    for (i in idx) {
      cat(.status_symbol(x$tests$status[[i]]), " ", x$tests$test[[i]],
          " [", .domain_label(x$tests$domain[[i]]), "]\n", sep = "")
      cat("  ", x$tests$observed[[i]], "\n", sep = "")
      if (nzchar(x$tests$details[[i]])) cat("  ", x$tests$details[[i]], "\n", sep = "")
    }
  } else {
    cat("\nAll registered tests passed. Use `print(x, details = TRUE)` for the complete audit trail.\n")
  }

  cat("\nCERTIFICATE STATUS: ", x$status, "\n", sep = "")
  cat("Certificate ID:     ", x$certificate_id, "\n", sep = "")
  cat("Data fingerprint:   ", x$data_fingerprint, "\n", sep = "")
  cat("Analysis fingerprint: ", x$analysis_fingerprint, "\n", sep = "")
  cat(strrep("-", 60), "\n", sep = "")
  cat(x$limitations[[1L]], "\n")
  invisible(x)
}

#' @export
summary.statwitness_audit <- function(object, ...) {
  counts <- table(factor(object$tests$status, levels = c("PASS", "WARN", "FAIL", "ERROR")))
  structure(list(
    status = object$status, model_type = object$model_type,
    focus = object$primary$label, primary = object$primary,
    counts = counts, domains = object$domains %||% .domain_summary(object$tests),
    failures = object$tests[object$tests$status %in% c("WARN", "FAIL", "ERROR"), , drop = FALSE]
  ), class = "summary.statwitness_audit")
}

#' @export
print.summary.statwitness_audit <- function(x, ...) {
  cat("statwitness summary\n")
  cat("Certificate: ", x$status, "\n", sep = "")
  cat("Model:       ", x$model_type, "\n", sep = "")
  cat("Focus:       ", x$focus, "\n", sep = "")
  if (x$primary$kind == "term") cat("Statistic:   ", .format_num(x$primary$statistic), "\n", sep = "") else
    cat("Estimate:    ", .format_num(x$primary$estimate), "\n", sep = "")
  cat("Tests:       ", paste(names(x$counts), as.integer(x$counts), sep = "=", collapse = ", "), "\n", sep = "")
  cat("\nDomains:\n")
  for (i in seq_len(nrow(x$domains))) {
    cat("- ", .domain_label(x$domains$domain[[i]]), ": ", x$domains$status[[i]], "\n", sep = "")
  }
  if (nrow(x$failures)) {
    cat("\nNon-passing findings:\n")
    for (i in seq_len(nrow(x$failures))) cat("- ", x$failures$test[[i]], ": ", x$failures$details[[i]], "\n", sep = "")
  }
  invisible(x)
}

#' @export
plot.statwitness_audit <- function(x, ...) {
  statuses <- factor(x$tests$status, levels = c("PASS", "WARN", "FAIL", "ERROR"))
  counts <- table(statuses)
  graphics::barplot(counts, main = paste("statwitness certificate:", x$status),
                    ylab = "Number of tests", xlab = "Test status", ...)
  invisible(counts)
}
