.test_binary_outcome_reversal <- function(info, tolerance) {
  d2 <- info$data
  yname <- info$response_name
  if (!info$response_simple || is.na(yname)) {
    return(.new_test(
      "binary_outcome_reversal", "Binary-outcome reversal", "ERROR",
      expected = "A simple 0/1 response variable.",
      observed = "The response is transformed or unavailable.",
      details = "Version 0.1 supports direct binary response columns only."
    ))
  }
  d2[[yname]] <- 1 - d2[[yname]]
  m2 <- .refit(info, d2)
  c1 <- stats::coef(info$model)
  c2 <- stats::coef(m2)
  ov <- .named_overlap(-c1, c2)
  p1 <- stats::fitted(info$model)
  p2 <- stats::fitted(m2)
  ok <- .within_tol(ov$x, ov$y, tolerance * 10) && .within_tol(p1, 1 - p2, tolerance * 10)
  .new_test(
    "binary_outcome_reversal", "Binary-outcome reversal", if (ok) "PASS" else "FAIL",
    expected = "All coefficients reverse sign and original probabilities equal one minus recoded probabilities.",
    observed = paste0(
      "maximum coefficient difference from sign reversal = ", .format_num(.max_abs_diff(ov$x, ov$y)),
      "; maximum probability identity error = ", .format_num(.max_abs_diff(p1, 1 - p2))
    ),
    details = if (ok) "Binary outcome reversal behaved as required by the logit model." else "The recoded binary model did not show the expected symmetry."
  )
}

.test_likelihood <- function(info, tolerance) {
  model <- info$model
  y <- stats::model.response(stats::model.frame(model))
  mu <- stats::fitted(model)
  w <- model$prior.weights %||% rep(1, length(y))
  reconstructed <- if (info$family == "binomial") {
    m <- w
    contribution_weight <- ifelse(m > 0, w / m, 0)
    sum(contribution_weight * stats::dbinom(
      round(m * y), size = round(m), prob = mu, log = TRUE
    ))
  } else if (info$family == "poisson") {
    sum(w * stats::dpois(y, lambda = mu, log = TRUE))
  } else {
    NA_real_
  }
  reported <- as.numeric(stats::logLik(model))
  ok <- .within_tol(reconstructed, reported, tolerance * 100)
  .new_test(
    "likelihood_reconstruction", "Independent log-likelihood reconstruction", if (ok) "PASS" else "FAIL",
    expected = "The reported likelihood matches a direct probability-mass calculation.",
    observed = paste0(
      "reported = ", .format_num(reported), "; reconstructed = ", .format_num(reconstructed),
      "; absolute difference = ", .format_num(abs(reported - reconstructed))
    ),
    details = if (ok) "The model likelihood was independently reconstructed." else "The reported likelihood differs from the reconstructed value."
  )
}
