#!/usr/bin/env Rscript

# Install only packages that are not already available.  Keeping dependency
# installation separate makes the computational part of the replication easy
# to rerun offline after the first successful setup.
# Pick a CRAN mirror.  A vanilla R session leaves the placeholder "@CRAN@"
# here, which install.packages() cannot resolve non-interactively, so a
# cold-start replicator needs an explicit fallback.
cran_mirror <- function() {
  cran <- getOption("repos")["CRAN"]
  if (is.na(cran) || identical(unname(cran), "@CRAN@")) "https://cloud.r-project.org" else unname(cran)
}

required_packages <- c(
  "BMS", "clubSandwich", "dplyr", "ggplot2", "lmtest",
  "sandwich", "scales", "tidyr"
)

missing_packages <- required_packages[
  !vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)
]

if (length(missing_packages)) {
  message("Installing missing packages: ", paste(missing_packages, collapse = ", "))
  install.packages(missing_packages, repos = cran_mirror())
}

still_missing <- required_packages[
  !vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)
]
if (length(still_missing)) {
  stop("Dependency installation failed for: ", paste(still_missing, collapse = ", "))
}

message("All R dependencies are available.")
