#!/usr/bin/env Rscript
# run_all.R — Component 7 · orchestrator for the whole chain
#
# Part of the Seed Longevity Lab's downloadable lab (site v0.17.0,
# longevity.seedsofhawaii.org/scripts). Pure interdependence: calls the sibling scripts in order and passes files between them.
#
# Standalone by design: the shared cores below are embedded verbatim in every
# script of the suite — no source() of siblings, no packages beyond base R
# (stats::glm is the probit engine).
# R 4.0+. Input: a raw completed-test CSV (one row per completed germination
# test) OR the suite's normalized_assays.csv interchange file.
#
# Same scientific contract as the Python scripts and the website engine, and
# cross-validated against both by the site's test suite. Each component's
# page card at /scripts spells out exactly where behavior differs from the
# archival workflow behind the published catalog.
#
# Counts rule, everywhere: actual number sown/tested + number germinated are
# required. Nothing in this suite ever assumes a sample size.

# ============================ command line ============================
main <- function() {
  args <- commandArgs(trailingOnly = TRUE)
  if (!length(args)) { cat("usage: Rscript run_all.R INPUT.csv [-o OUTDIR] [--time-unit U]\n"); quit(status = 1) }
  outdir <- if ("-o" %in% args) args[which(args == "-o") + 1] else "longevity_lab_output"
  tu <- if ("--time-unit" %in% args) c("--time-unit", args[which(args == "--time-unit") + 1]) else character(0)
  here <- dirname(sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE)[1]))
  dir.create(outdir, showWarnings = FALSE, recursive = TRUE)
  norm <- file.path(outdir, "normalized_assays.csv")
  run <- function(script, argv, optional = FALSE) {
    path <- file.path(here, script)
    if (!file.exists(path)) { message(sprintf("[SKIP] %s not found next to run_all.R", script)); return(invisible()) }
    code <- system2("Rscript", c(path, argv))
    if (code != 0 && !optional) quit(status = code)
  }
  run("longevity_normalize.R", c(args[1], "-o", norm, tu))
  run("longevity_rci.R", c(norm, "-o", outdir))
  run("longevity_formal.R", c(norm, "-o", outdir, "--thresholds", file.path(outdir, "rci_accession_intervals.csv")))
  run("longevity_shared_ki.R", c(norm, "-o", outdir))
  run("longevity_models.R", c(norm, "-o", outdir))
  run("longevity_plots.R", c(norm, "-o", file.path(outdir, "plots")), optional = TRUE)
  cat(sprintf("\nComplete. Everything is under %s/.\n", outdir))
}
main()
