.test_group_label_invariance <- function(info, variable, tolerance) {
  d2 <- info$data
  x <- factor(d2[[variable]])
  levels(x) <- paste0("SW_GROUP_", seq_along(levels(x)))
  d2[[variable]] <- x
  m2 <- .refit(info, d2)
  ov <- .named_overlap(.fixed_coef(info$model), .fixed_coef(m2))
  ll1 <- .model_loglik(info$model)
  ll2 <- .model_loglik(m2)
  ok <- .within_tol(ov$x, ov$y, tolerance * 100) && .within_tol(ll1, ll2, tolerance * 100)
  .new_test(
    "group_label_invariance", paste0("Grouping-label invariance: ", variable), if (ok) "PASS" else "FAIL",
    expected = "Renaming cluster labels preserves fixed effects and likelihood.",
    observed = paste0("maximum fixed-effect difference = ", .format_num(.max_abs_diff(ov$x, ov$y)),
                      "; likelihood difference = ", .format_num(abs(ll1 - ll2))),
    details = if (ok) "Random-effect grouping labels were treated as identifiers." else "Renaming grouping labels changed the mixed model."
  )
}

.test_mixed_convergence <- function(info) {
  model <- info$model
  status <- "PASS"
  observed <- "No convergence problem was reported."
  details <- "The optimizer diagnostics did not report a convergence failure."
  if (info$model_class %in% c("lmerMod", "glmerMod")) {
    msgs <- model@optinfo$conv$lme4$messages
    code <- model@optinfo$conv$opt
    if (!is.null(msgs) || (!is.null(code) && any(code != 0))) {
      status <- "WARN"
      observed <- paste(c(msgs, paste0("optimizer code: ", paste(code, collapse = ", "))), collapse = "; ")
      details <- "The mixed model reported a convergence warning; estimates require review."
    }
  } else if (info$model_class == "glmmTMB") {
    code <- info$model$fit$convergence
    pdh <- tryCatch(info$model$sdr$pdHess, error = function(e) NA)
    if (!identical(code, 0L) || isFALSE(pdh)) {
      status <- "WARN"
      observed <- paste0("optimizer code = ", code, "; positive-definite Hessian = ", pdh)
      details <- "The glmmTMB fit reported convergence or Hessian concerns."
    }
  }
  .new_test(
    "mixed_convergence", "Mixed-model convergence audit", status, severity = "warning",
    expected = "A successful optimizer termination without unresolved convergence messages.",
    observed = observed, details = details
  )
}

.test_mixed_singularity <- function(info, tolerance) {
  if (info$model_class %in% c("lmerMod", "glmerMod")) {
    singular <- lme4::isSingular(info$model, tol = max(tolerance, 1e-5))
    return(.new_test(
      "mixed_singularity", "Random-effects singularity audit", if (singular) "WARN" else "PASS",
      severity = "warning",
      expected = "The requested random-effects covariance structure is supported away from its boundary.",
      observed = paste0("singular fit = ", singular),
      details = if (singular) "At least one random-effects dimension is on or near the boundary; the random structure may be more complex than the data support." else "No singular random-effects structure was detected."
    ))
  }
  vc <- tryCatch(glmmTMB::VarCorr(info$model), error = function(e) NULL)
  near_zero <- FALSE
  if (!is.null(vc)) {
    vals <- suppressWarnings(as.numeric(unlist(vc)))
    vals <- vals[is.finite(vals)]
    near_zero <- length(vals) && any(abs(vals) < max(tolerance, 1e-8))
  }
  .new_test(
    "mixed_singularity", "Random-effects boundary audit", if (near_zero) "WARN" else "PASS",
    severity = "warning",
    expected = "No estimated random-effect variance lies effectively at zero.",
    observed = paste0("near-zero variance detected = ", near_zero),
    details = if (near_zero) "A random-effect variance appears to be on the boundary." else "No obvious random-effect boundary estimate was detected."
  )
}

.test_optimizer_agreement <- function(info, tolerance) {
  if (!info$model_class %in% c("lmerMod", "glmerMod")) {
    return(.new_test("optimizer_agreement", "Alternative-optimizer agreement", "WARN", severity = "warning",
      expected = "A registered alternative optimizer is available.", observed = "No alternative optimizer adapter is registered.",
      details = "Optimizer agreement is currently implemented for lme4 models."))
  }
  if (info$model_class == "lmerMod") {
    ctrl <- lme4::lmerControl(optimizer = "bobyqa")
  } else {
    ctrl <- lme4::glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 2e5))
  }
  m2 <- .refit(info, info$data, control = ctrl)
  ov <- .named_overlap(.fixed_coef(info$model), .fixed_coef(m2))
  ll1 <- .model_loglik(info$model)
  ll2 <- .model_loglik(m2)
  ok <- .within_tol(ov$x, ov$y, max(tolerance * 1000, 1e-5)) &&
    .within_tol(ll1, ll2, max(tolerance * 1000, 1e-5))
  .new_test(
    "optimizer_agreement", "Alternative-optimizer agreement", if (ok) "PASS" else "WARN",
    severity = "warning",
    expected = "A second optimizer reaches materially equivalent fixed effects and likelihood.",
    observed = paste0("maximum fixed-effect difference = ", .format_num(.max_abs_diff(ov$x, ov$y)),
                      "; likelihood difference = ", .format_num(abs(ll1 - ll2))),
    details = if (ok) "The alternative optimizer reached an equivalent solution." else "The alternative optimizer reached a materially different solution or local optimum."
  )
}

.test_random_structure <- function(info) {
  if (!info$model_class %in% c("lmerMod", "glmerMod")) {
    return(.new_test("random_structure", "Random-effects structure summary", "PASS", severity = "warning",
      expected = "Random-effect variance information is available.", observed = "Model-specific variance information recorded.",
      details = "Review the model object's variance-covariance summary for boundary estimates."))
  }
  vc <- as.data.frame(lme4::VarCorr(info$model))
  zero <- vc$vcov < 1e-8
  corr_boundary <- !is.na(vc$var2) & abs(vc$sdcor) > 0.999
  issue <- any(zero | corr_boundary)
  observed <- paste0("variance components = ", nrow(vc),
                     "; near-zero components = ", sum(zero),
                     "; boundary correlations = ", sum(corr_boundary))
  .new_test(
    "random_structure", "Random-effects structure summary", if (issue) "WARN" else "PASS",
    severity = "warning",
    expected = "No near-zero variance component or near-perfect random-effect correlation.",
    observed = observed,
    details = if (issue) "The random-effects structure contains a boundary-like component that merits review." else "No obvious boundary-like random-effect component was found."
  )
}
