# PSYCH 10 local R setup
# Run this file once from RStudio by clicking Source.

options(repos = c(CRAN = "https://cloud.r-project.org"))

expected_r_version <- "4.6.1"

# Packages used directly in PSYCH 10 materials. coursekata loads its core
# packages (including supernova, mosaic, ggformula, dplyr, and Metrics).
psych10_packages <- c(
  "coursekata",
  "rmarkdown",
  "knitr",
  "tinytex",
  "here",
  "ggpubr",
  "gridExtra",
  "lme4",
  "plotly",
  "statmod"
)

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

if (length(missing_packages) > 0) {
  message("Installing: ", paste(missing_packages, collapse = ", "))
  # The default installs required dependencies without pulling in every
  # optional "Suggests" package, which keeps student setup manageable.
  install.packages(missing_packages)
} else {
  message("All main PSYCH 10 packages are already installed.")
}

# Install the supplementary datasets used by CourseKata materials, including
# fivethirtyeight, fivethirtyeightdata, Lock5withR, and dslabs.
if (requireNamespace("coursekata", quietly = TRUE)) {
  coursekata::coursekata_install()
}

# R Markdown uses LaTeX to create PDF files. The tinytex R package is the
# installer/manager; TinyTeX itself is the LaTeX distribution. Install a fresh,
# consistent TinyTeX bundle only when one is not already available.
if (requireNamespace("tinytex", quietly = TRUE) &&
    !tinytex::is_tinytex()) {
  message("Installing TinyTeX for knitting R Markdown files to PDF...")
  tinytex::install_tinytex(force = TRUE, extra_packages = NULL)
}

# Verify the core setup and give the student an unambiguous result.
core_packages <- c(
  "coursekata",
  "supernova",
  "mosaic",
  "ggformula",
  "dplyr",
  "Metrics"
)

all_packages <- unique(c(psych10_packages, core_packages))
package_ok <- vapply(
  all_packages,
  requireNamespace,
  logical(1),
  quietly = TRUE
)

r_version_ok <- identical(
  paste(R.version$major, R.version$minor, sep = "."),
  expected_r_version
)

pdf_knitting_ok <- requireNamespace("tinytex", quietly = TRUE) &&
  tinytex::is_tinytex()

cat("\n")
if (all(package_ok) && r_version_ok && pdf_knitting_ok) {
  suppressPackageStartupMessages(library(coursekata))
  stopifnot(is.data.frame(Fingers), nrow(Fingers) > 0)

  cat("================================\n")
  cat("  PSYCH 10 SETUP SUCCEEDED\n")
  cat("================================\n")
  cat("R version: ", R.version.string, "\n", sep = "")
  cat("coursekata version: ",
      as.character(utils::packageVersion("coursekata")), "\n", sep = "")
  cat("PDF knitting: ready\n")
  cat("You may close this file and begin your lab.\n")
} else {
  cat("========================================\n")
  cat("  PSYCH 10 SETUP NEEDS ATTENTION\n")
  cat("========================================\n")
  if (!r_version_ok) {
    cat("Expected R version: ", expected_r_version, "\n", sep = "")
    cat("Your R version: ", paste(R.version$major, R.version$minor, sep = "."),
        "\n", sep = "")
  }
  if (!all(package_ok)) {
    cat("These packages are still unavailable:\n  ",
        paste(names(package_ok)[!package_ok], collapse = ", "), "\n", sep = "")
  }
  if (!pdf_knitting_ok) {
    cat("TinyTeX is not ready, so R Markdown cannot yet knit to PDF.\n")
  }
  cat("Copy the Console output and send it to the teaching team.\n")
}
