test_that("linear-model audit returns a certificate", {
  dat <- transform(mtcars, transmission = factor(am))

  out <- statwitness(
    mpg ~ transmission + wt + hp,
    data = dat,
    focus = "transmission"
  )

  expect_s3_class(out, "statwitness_audit")
  expect_true(out$status %in% c("PASSED", "WARNING"))
  expect_true(all(c("test", "status", "domain", "observed") %in% names(out$tests)))
  expect_true(any(out$tests$id == "known_effect_injection"))
  expect_match(out$certificate_id, "^SW-[A-F0-9]{12}$")
  expect_equal(nchar(out$data_fingerprint), 32L)
  expect_false(any(out$tests$status %in% c("FAIL", "ERROR")))
})

test_that("ANOVA-like factor design is detected", {
  out <- statwitness(
    breaks ~ wool * tension,
    data = warpbreaks,
    focus = "wool"
  )

  expect_identical(out$model_type, "anova_linear_model")
  expect_true(any(out$tests$id == "anova_cell_audit"))
  expect_false(any(out$tests$status %in% c("FAIL", "ERROR")))
})

test_that("bare weight column is supported", {
  dat <- transform(mtcars, w = seq_len(nrow(mtcars)) / nrow(mtcars))
  out <- statwitness(mpg ~ wt + hp, data = dat, focus = "wt", weights = w)
  expect_s3_class(out, "statwitness_audit")
  expect_false(any(out$tests$status %in% c("FAIL", "ERROR")))
})

test_that("custom engine that ignores weights is detected", {
  dat <- transform(mtcars, w = seq_len(nrow(mtcars)))
  bad_engine <- function(formula, data, family = NULL, weights = NULL) {
    stats::lm(formula, data = data, model = TRUE, x = TRUE, y = TRUE)
  }

  out <- statwitness(
    mpg ~ wt + hp,
    data = dat,
    focus = "wt",
    weights = w,
    engine = bad_engine
  )

  weight_test <- out$tests[out$tests$id == "weight_semantics", , drop = FALSE]
  expect_identical(weight_test$status, "FAIL")
  expect_identical(out$status, "FAILED")
})
