.infer_focus <- function(model, fixed_formula, data, focus = NULL) {
  coefs <- .fixed_coef(model)
  coef_names <- names(coefs)
  term_labels <- attr(stats::terms(fixed_formula), "term.labels")
  candidates <- coef_names[coef_names != "(Intercept)" & !is.na(coefs)]

  if (is.null(focus)) {
    if (!length(candidates)) .sw_abort("The fitted model has no non-intercept coefficient to audit.")
    return(list(variable = candidates[[1L]], coefficient = candidates[[1L]],
                term = NA_character_, kind = "coefficient", inferred = TRUE))
  }

  focus <- as.character(focus)[[1L]]
  if (focus %in% coef_names) {
    return(list(variable = focus, coefficient = focus, term = NA_character_,
                kind = "coefficient", inferred = FALSE))
  }
  if (focus %in% names(data)) {
    matches <- coef_names[startsWith(coef_names, focus)]
    matches <- matches[!grepl(":", matches, fixed = TRUE)]
    matches <- matches[!is.na(coefs[matches])]
    if (length(matches) == 1L) {
      return(list(variable = focus, coefficient = matches[[1L]], term = NA_character_,
                  kind = "coefficient", inferred = FALSE))
    }
    if (length(matches) > 1L) {
      return(list(variable = focus, coefficient = NA_character_, term = focus,
                  kind = "term", inferred = FALSE))
    }
  }
  if (focus %in% term_labels) {
    return(list(variable = focus, coefficient = NA_character_, term = focus,
                kind = "term", inferred = FALSE))
  }

  .sw_abort(
    "Could not match `focus`. Available terms are: ", paste(term_labels, collapse = ", "),
    ". Available coefficients are: ", paste(coef_names, collapse = ", "), "."
  )
}

.inspect_analysis <- function(model, formula, data, focus, weights, engine,
                              method, control) {
  fixed_formula <- .fixed_formula(formula)
  trm <- stats::terms(fixed_formula)
  labels <- attr(trm, "term.labels")
  response_expr <- fixed_formula[[2L]]
  response_simple <- is.symbol(response_expr)
  response_name <- if (response_simple) as.character(response_expr) else NA_character_
  all_predictors <- all.vars(stats::delete.response(trm))
  simple_predictors <- intersect(labels, names(data))
  numeric_predictors <- simple_predictors[vapply(data[simple_predictors], function(x) {
    is.numeric(x) || is.integer(x)
  }, logical(1))]
  factor_predictors <- simple_predictors[vapply(data[simple_predictors], function(x) {
    is.factor(x) || is.character(x) || is.logical(x)
  }, logical(1))]
  simple_only_predictors <- simple_predictors[vapply(simple_predictors, function(v) {
    uses <- vapply(labels, function(lbl) {
      v %in% all.vars(stats::as.formula(paste("~", lbl)))
    }, logical(1))
    sum(uses) == 1L && identical(labels[uses], v)
  }, logical(1))]

  focus_info <- .infer_focus(model, fixed_formula, data, focus)
  focus_var <- focus_info$variable
  focus_in_interaction <- any(grepl(":", labels, fixed = TRUE) &
    vapply(strsplit(labels, ":", fixed = TRUE), function(x) focus_var %in% x, logical(1)))
  focus_binary_factor <- focus_var %in% names(data) &&
    (is.factor(data[[focus_var]]) || is.character(data[[focus_var]]) || is.logical(data[[focus_var]])) &&
    length(unique(stats::na.omit(data[[focus_var]]))) == 2L

  id <- .model_class_id(model)
  fam <- .model_family_info(model)
  all_factor_design <- length(simple_predictors) >= 1L &&
    length(simple_predictors) == length(factor_predictors)
  is_mixed <- id %in% c("lmerMod", "glmerMod", "glmmTMB")
  is_survival <- id %in% c("coxph", "survreg")
  model_type <- switch(
    id,
    lm = if (all_factor_design) "anova_linear_model" else "linear_model",
    aov = "classical_anova",
    glm = paste0(fam$family, "_glm"),
    lmerMod = "linear_mixed_model",
    glmerMod = paste0(fam$family, "_generalized_mixed_model"),
    glmmTMB = paste0(fam$family, "_glmmTMB_model"),
    coxph = "cox_proportional_hazards",
    survreg = "parametric_survival_model",
    id
  )

  list(
    model = model, formula = formula, fixed_formula = fixed_formula, data = data,
    weights = weights, weights_supplied = !is.null(weights),
    engine = engine %||% .default_engine, method = method, control = control,
    family_object = fam$object, model_class = id, model_type = model_type,
    family = fam$family, link = fam$link, terms = trm, term_labels = labels,
    has_intercept = attr(trm, "intercept") == 1L,
    response_expr = response_expr, response_simple = response_simple,
    response_name = response_name, response_variables = .response_variables(formula),
    all_predictors = all_predictors, simple_predictors = simple_predictors,
    simple_only_predictors = simple_only_predictors,
    numeric_predictors = numeric_predictors, factor_predictors = factor_predictors,
    has_interactions = any(grepl(":", labels, fixed = TRUE)),
    focus = focus_var, focus_coef = focus_info$coefficient,
    focus_term = focus_info$term, focus_kind = focus_info$kind,
    focus_inferred = focus_info$inferred,
    focus_in_interaction = focus_in_interaction,
    focus_binary_factor = focus_binary_factor,
    all_factor_design = all_factor_design,
    is_mixed = is_mixed, is_survival = is_survival,
    random_groups = .random_group_vars(formula)
  )
}

.term_lrt <- function(info, term) {
  reduced_formula <- stats::update.formula(info$formula, paste(". ~ . -", term))
  full <- info$model
  if (info$model_class == "lmerMod") {
    full_args <- list(formula = info$formula, data = info$data,
                      REML = FALSE, na.action = stats::na.omit)
    reduced_args <- list(formula = reduced_formula, data = info$data,
                         REML = FALSE, na.action = stats::na.omit)
    if (!is.null(info$weights)) {
      full_args$weights <- info$weights
      reduced_args$weights <- info$weights
    }
    full <- do.call(lme4::lmer, full_args)
    reduced <- do.call(lme4::lmer, reduced_args)
  } else {
    reduced <- .refit(info, info$data, formula = reduced_formula)
  }
  tab <- stats::anova(reduced, full)
  pcol <- grep("Pr\\(", colnames(tab), value = TRUE)
  statcol <- intersect(c("Chisq", "L.Ratio", "F"), colnames(tab))
  dfcol <- intersect(c("Chi Df", "Df"), colnames(tab))
  list(
    statistic = if (length(statcol)) unname(tab[nrow(tab), statcol[[1L]]]) else NA_real_,
    df = if (length(dfcol)) unname(tab[nrow(tab), dfcol[[1L]]]) else NA_real_,
    p_value = if (length(pcol)) unname(tab[nrow(tab), pcol[[1L]]]) else NA_real_,
    method = "full-versus-reduced likelihood-ratio test"
  )
}

.term_test_lm <- function(info, term) {
  test <- if (info$model_class %in% c("lm", "aov")) "F" else "Chisq"
  tab <- tryCatch(stats::drop1(info$model, test = test), error = function(e) NULL)
  if (is.null(tab) || !term %in% rownames(tab)) {
    tab <- if (info$model_class == "glm") stats::anova(info$model, test = "Chisq") else stats::anova(info$model)
  }
  rn <- rownames(tab)
  idx <- which(rn == term)
  if (!length(idx)) .sw_abort("The omnibus term `", term, "` could not be isolated under the model hierarchy.")
  pcol <- grep("Pr\\(", colnames(tab), value = TRUE)
  statcol <- intersect(c("F value", "LRT"), colnames(tab))
  dfcol <- intersect(c("Df"), colnames(tab))
  list(
    statistic = if (length(statcol)) unname(tab[idx[[1L]], statcol[[1L]]]) else NA_real_,
    df = if (length(dfcol)) unname(tab[idx[[1L]], dfcol[[1L]]]) else NA_real_,
    p_value = if (length(pcol)) unname(tab[idx[[1L]], pcol[[1L]]]) else NA_real_,
    method = paste0("drop-one ", test, " test")
  )
}

.primary_result <- function(info, conf_level = 0.95) {
  if (info$focus_kind == "term") {
    tt <- if (info$model_class %in% c("lm", "aov", "glm")) {
      .term_test_lm(info, info$focus_term)
    } else {
      .term_lrt(info, info$focus_term)
    }
    return(list(
      kind = "term", label = info$focus_term, coefficient = NA_character_,
      estimate = NA_real_, standard_error = NA_real_, statistic = tt$statistic,
      df = tt$df, p_value = tt$p_value, conf_level = conf_level,
      lower = NA_real_, upper = NA_real_, transformed = NULL,
      n = .model_nobs(info$model), method = tt$method
    ))
  }

  beta <- .fixed_coef(info$model)
  V <- .fixed_vcov(info$model)
  if (!info$focus_coef %in% names(beta)) {
    .sw_abort("The focus coefficient is not estimable in the fitted model.")
  }
  estimate <- unname(beta[[info$focus_coef]])
  se <- sqrt(unname(V[info$focus_coef, info$focus_coef]))
  statistic <- estimate / se
  pvals <- .model_p_values(info$model)
  p_value <- if (info$focus_coef %in% names(pvals)) pvals[[info$focus_coef]] else 2 * stats::pnorm(abs(statistic), lower.tail = FALSE)
  alpha <- 1 - conf_level
  critical <- if (info$model_class %in% c("lm", "aov")) {
    stats::qt(1 - alpha / 2, df = stats::df.residual(info$model))
  } else {
    stats::qnorm(1 - alpha / 2)
  }
  lower <- estimate - critical * se
  upper <- estimate + critical * se
  transformed <- NULL
  if (info$link == "logit") {
    transformed <- list(label = "odds ratio", estimate = exp(estimate), lower = exp(lower), upper = exp(upper))
  } else if (info$link %in% c("log", "log-hazard")) {
    transformed <- list(label = if (info$link == "log-hazard") "hazard ratio" else "rate ratio",
                        estimate = exp(estimate), lower = exp(lower), upper = exp(upper))
  }
  list(
    kind = "coefficient", label = info$focus_coef, coefficient = info$focus_coef,
    estimate = estimate, standard_error = se, statistic = statistic, df = NA_real_,
    p_value = p_value, conf_level = conf_level, lower = lower, upper = upper,
    transformed = transformed, n = .model_nobs(info$model), method = "coefficient-level Wald inference"
  )
}
