test_that("default engine is rstan", {
  withr::local_options(list(mlumr.stan_engine = NULL))
  expect_equal(mlumr_engine(), "rstan")
})

test_that("setting engine to rstan works", {
  withr::local_options(list(mlumr.stan_engine = NULL))
  mlumr_engine("rstan")
  expect_equal(mlumr_engine(), "rstan")
})

test_that("setting engine to invalid value errors", {
  expect_error(mlumr_engine("jags"), "`engine` must be 'rstan' or 'cmdstanr'")
  expect_error(mlumr_engine("c"), "`engine` must be 'rstan' or 'cmdstanr'")
  expect_error(mlumr_engine(c("rstan", "cmdstanr")),
               "`engine` must be 'rstan' or 'cmdstanr'")
})

test_that("get_engine returns option value", {
  withr::local_options(list(mlumr.stan_engine = "cmdstanr"))
  expect_equal(mlumr:::get_engine(), "cmdstanr")
})

test_that("get_engine rejects invalid option values", {
  withr::local_options(list(mlumr.stan_engine = "bad"))
  expect_error(mlumr:::get_engine(), "`engine` must be 'rstan' or 'cmdstanr'")
})

test_that("unchanged-engine message tolerates invalid option values", {
  withr::local_options(list(mlumr.stan_engine = "bad"))
  expect_message(value <- mlumr:::.message_engine_unchanged(),
                 "Engine unchanged \\(invalid current option\\)")
  expect_true(is.na(value))
})

test_that("get_engine defaults to rstan when option is NULL", {
  withr::local_options(list(mlumr.stan_engine = NULL))
  expect_equal(mlumr:::get_engine(), "rstan")
})


test_that("cmdstanr backend fits a model end-to-end", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")
  skip_if_not(
    tryCatch({ cmdstanr::cmdstan_path(); TRUE }, error = function(e) FALSE),
    "CmdStan not available"
  )

  set.seed(42)
  n <- 50
  x1 <- rbinom(n, 1, 0.5)
  y <- rbinom(n, 1, plogis(-0.5 + 0.8 * x1))
  ipd_df <- data.frame(trt = "A", outcome = y, x1 = x1)
  agd_df <- data.frame(trt = "B", n_total = 100, n_events = 35, x1_mean = 0.4)

  ipd <- set_ipd(ipd_df, "trt", "outcome", "x1")
  agd <- set_agd(agd_df, "trt", outcome_n = "n_total",
                 outcome_r = "n_events", cov_means = "x1_mean")
  dat <- combine_data(ipd, agd)
  dat <- add_integration(dat, n_int = 32,
                         x1 = distr(qbern, prob = x1_mean))

  fit <- mlumr(dat, model = "spfa", engine = "cmdstanr",
               chains = 2, iter = 500, warmup = 250, refresh = 0, seed = 123)

  expect_s3_class(fit, "mlumr_fit")
  expect_equal(fit$family, "binomial")
  expect_equal(fit$engine, "cmdstanr")
  expect_true("mu_index" %in% names(fit$draws))
  expect_true("variable" %in% names(fit$summary))
  expect_true("mean" %in% names(fit$summary))
  expect_true("Rhat" %in% names(fit$summary))
  expect_true(is.numeric(fit$diagnostics$n_divergent))
  expect_true(is.numeric(fit$diagnostics$n_max_treedepth))
  expect_false(file.exists(file.path("inst", "stan", "mlumr_binary_spfa")))
})
