setup_file <- if (file.exists('00_script_setup.R')) '00_script_setup.R' else file.path('scripts', '00_script_setup.R')
source(setup_file)

#### Code to install project packages for the voting for democracy R&R analyses.
#### Installs packages into the project-local r-lib folder.

### Packages and library path----

project_root <- getwd()
local_lib <- file.path(project_root, "r-lib")

dir.create(local_lib, showWarnings = FALSE, recursive = TRUE)
.libPaths(c(local_lib, .libPaths()))

required_pkgs <- c(
  "dplyr", "tidyr", "tibble", "ggplot2", "sandwich", "lmtest",
  "here", "forcats", "cregg", "texreg", "knitr", "lavaan",
  "psych", "readr", "survey", "ggstance", "mitools", "DBI"
)

### Install missing packages----

available_pkgs <- available.packages(repos = "https://cloud.r-project.org")
dep_list <- tools::package_dependencies(
  required_pkgs,
  db = available_pkgs,
  which = c("Depends", "Imports", "LinkingTo"),
  recursive = TRUE
)
all_needed <- unique(c(required_pkgs, unlist(dep_list)))
all_needed <- all_needed[!all_needed %in% c("R", "base", "compiler", "datasets",
                                            "graphics", "grDevices", "grid",
                                            "methods", "parallel", "splines",
                                            "stats", "stats4", "tools", "utils")]

installed_now <- rownames(installed.packages(lib.loc = local_lib))
missing_pkgs <- setdiff(all_needed, installed_now)

print(.libPaths())
print(missing_pkgs)

if (length(missing_pkgs) > 0) {
  install.packages(
    missing_pkgs,
    lib = local_lib,
    repos = "https://cloud.r-project.org",
    dependencies = TRUE
  )
}

### Check installed packages----

check <- data.frame(
  package = required_pkgs,
  installed_local = required_pkgs %in% rownames(installed.packages(lib.loc = local_lib)),
  installed_anywhere = sapply(required_pkgs, requireNamespace, quietly = TRUE),
  row.names = NULL
)

print(check)
