dem_cultures_scripts <- c(
  "dem cultures code 1 measures v2.R",
  "dem cultures code 2 conjoint v2.R",
  "dem cultures code 3 atme v2.R",
  "dem cultures code 3.1 atme loo v3.R",
  "dem cultures code 3.2 atme v2.R",
  "dem cultures code 4 lpms v2.R",
  "dem cultures code 4.1 lpms loo v2.R",
  "dem cultures code 4.2 lpms v2.R",
  "dem cultures code 5 nonparam v2.R",
  "dem cultures code 7 background v3.R",
  "dem cultures code 9 logit effs v2.R",
  "dem cultures code 9.1 first diffs v3.R",
  "dem cultures code 10 add analyses v3.R"
)

current_dir <- normalizePath(getwd(), winslash = "/", mustWork = TRUE)
cmd_file <- grep("^--file=", commandArgs(trailingOnly = FALSE), value = TRUE)
script_dir <- if (length(cmd_file) > 0) {
  dirname(normalizePath(sub("^--file=", "", cmd_file[1]),
                        winslash = "/", mustWork = TRUE))
} else if (!is.null(sys.frames()[[1]]$ofile)) {
  dirname(normalizePath(sys.frames()[[1]]$ofile,
                        winslash = "/", mustWork = TRUE))
} else {
  NA_character_
}

candidate_roots <- unique(c(
  current_dir,
  dirname(current_dir),
  if (!is.na(script_dir)) script_dir,
  if (!is.na(script_dir)) dirname(script_dir)
))
candidate_roots <- normalizePath(candidate_roots, winslash = "/",
                                 mustWork = FALSE)

has_replication_files <- function(root) {
  dir.exists(file.path(root, "data")) &&
    all(file.exists(file.path(root, "scripts", dem_cultures_scripts)))
}

root_match <- candidate_roots[vapply(candidate_roots, has_replication_files,
                                     logical(1))]
if (length(root_match) == 0) {
  stop(
    "Could not locate the replication-materials root. Tried: ",
    paste(candidate_roots, collapse = "; "),
    ". Please run this file from the replication materials folder or its scripts subfolder."
  )
}

project_root <- root_match[1]
setwd(project_root)
dir.create(file.path(project_root, "data"), showWarnings = FALSE)
dir.create(file.path(project_root, "outputs"), showWarnings = FALSE)
local_lib <- file.path(project_root, "r-lib")
dir.create(local_lib, showWarnings = FALSE, recursive = TRUE)
.libPaths(c(local_lib, .libPaths()))

required_cran_pkgs <- c(
  "dplyr",
  "forcats",
  "ggplot2",
  "here",
  "lavaan",
  "lmtest",
  "remotes",
  "psych",
  "sandwich",
  "texreg",
  "tibble",
  "tidyr"
)
required_github_pkgs <- c(
  cregg = "leeper/cregg@090689064d76e37b525eb1204633e219c69e659d"
)
required_base_pkgs <- c("grid", "stats", "utils")

missing_base_pkgs <- required_base_pkgs[
  !vapply(required_base_pkgs, requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_base_pkgs) > 0) {
  stop("Required base/recommended R packages are unavailable: ",
       paste(missing_base_pkgs, collapse = ", "))
}

missing_cran_pkgs <- required_cran_pkgs[
  !vapply(required_cran_pkgs, requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_cran_pkgs) > 0) {
  message("Installing missing CRAN packages into ", local_lib, ": ",
          paste(missing_cran_pkgs, collapse = ", "))
  install.packages(
    missing_cran_pkgs,
    lib = local_lib,
    repos = "https://cloud.r-project.org",
    dependencies = c("Depends", "Imports", "LinkingTo")
  )
}

unavailable_cran_pkgs <- required_cran_pkgs[
  !vapply(required_cran_pkgs, requireNamespace, logical(1), quietly = TRUE)
]
if (length(unavailable_cran_pkgs) > 0) {
  stop("The following required packages could not be loaded after installation: ",
       paste(unavailable_cran_pkgs, collapse = ", "))
}

missing_github_pkgs <- names(required_github_pkgs)[
  !vapply(names(required_github_pkgs), requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_github_pkgs) > 0) {
  for (pkg in missing_github_pkgs) {
    message("Installing ", pkg, " from GitHub into ", local_lib, ": ",
            required_github_pkgs[[pkg]])
    remotes::install_github(
      required_github_pkgs[[pkg]],
      lib = local_lib,
      dependencies = c("Depends", "Imports", "LinkingTo"),
      upgrade = "never"
    )
  }
}

unavailable_github_pkgs <- names(required_github_pkgs)[
  !vapply(names(required_github_pkgs), requireNamespace, logical(1), quietly = TRUE)
]
if (length(unavailable_github_pkgs) > 0) {
  stop("The following required GitHub packages could not be loaded after installation: ",
       paste(unavailable_github_pkgs, collapse = ", "))
}

library(here)

for (script in dem_cultures_scripts) {
  script_path <- file.path(project_root, "scripts", script)
  if (!file.exists(script_path)) {
    stop("Missing required script: ", script_path)
  }
  message("Running ", script)
  source(script_path, local = new.env(parent = globalenv()), echo = FALSE)
}

message("All dem cultures replication scripts completed.")
