test_that("HeckmanBS analytical gradient agrees with independent score", {
  testthat::skip_on_cran()
  testthat::skip_if_not_installed("numDeriv")

  data("MEPS2001", package = "ssmodels")
  dados <- as.data.frame(MEPS2001)

  selectEq <- dambexp ~ age + female + educ + blhisp + totchr + ins + income
  outcomeBS <- ambexp ~ age + female + educ + blhisp + totchr + ins

  validation_file <- system.file(
    "validation",
    "HeckmanBS_loglik_score_independente.R",
    package = "ssmodels"
  )
  testthat::skip_if(validation_file == "", "HeckmanBS validation helper not installed")
  source(validation_file, local = TRUE)

  components_bs <- heckmanBS_prepare(selectEq, outcomeBS, dados)
  fit_bs <- ssmodels::HeckmanBS(selection = selectEq, outcome = outcomeBS, data = dados)

  theta_link <- fit_bs$coefficients_link
  names(theta_link) <- c(
    paste0("gamma:", colnames(components_bs$XS)),
    paste0("beta:", colnames(components_bs$XO)),
    "phi1",
    "rho_star"
  )

  score_independent <- heckmanBS_score_independente(
    theta_link, selectEq, outcomeBS, dados, components_bs
  )
  score_numeric <- numDeriv::grad(
    func = heckmanBS_loglik_independente,
    x = theta_link,
    selection = selectEq,
    outcome = outcomeBS,
    data = dados,
    components = components_bs,
    method = "Richardson"
  )

  package_error <- max(abs(as.numeric(fit_bs$gradient_link) - as.numeric(score_independent)))
  numeric_error <- max(abs(as.numeric(score_independent) - as.numeric(score_numeric)))

  testthat::expect_true(all(is.finite(fit_bs$gradient_link)))
  testthat::expect_lt(package_error, 1e-7)
  testthat::expect_lt(numeric_error, 1e-4)
})
