source("renv/activate.R")
if (!nzchar(Sys.getenv("CI"))) {
  local({
    cli_cmd <- paste(commandArgs(trailingOnly = FALSE), collapse = " ")
    if (grepl("renv::restore|run_manuscript\\.R", cli_cmd)) {
      return(invisible(NULL))
    }
    is_binary_os <- identical(.Platform$OS.type, "windows") || grepl("^darwin", R.version$os)
    required_pkgs <- c(
      "knitr", "rmarkdown", "pROC", "dplyr", "tidyr", "ggplot2",
      "gt", "gtsummary", "dcurves", "CalibrationCurves",
      "pmvalsampsize", "rms", "gridExtra", "synthpop", "reticulate", "shiny", "bslib"
    )
    missing_pkgs <- required_pkgs[!vapply(required_pkgs, requireNamespace, logical(1), quietly = TRUE)]
    if (length(missing_pkgs) > 0) {
      if (is_binary_os) {
        message(
          "First-time setup for R ", getRversion(), ": installing precompiled binary packages (",
          paste(missing_pkgs, collapse = ", "), ")..."
        )
        try(utils::install.packages(missing_pkgs, repos = "https://cloud.r-project.org", type = "binary"))
      } else {
        message(
          "Missing R packages detected (", paste(missing_pkgs, collapse = ", "), "). ",
          "Run renv::restore(prompt = FALSE) to restore the locked environment from renv.lock."
        )
      }
    }
  })
}
