#!/usr/bin/env Rscript

# Single entry point ---------------------------------------------------------
# Run with `Rscript run_all.R` from this directory or from any other working
# directory.  The script resolves its own location and never reaches into the
# parent research repository.

# USER OPTION: BMA run length ------------------------------------------------
# Leave this FALSE for the publication-quality replication. Change it to TRUE
# only when checking that the workflow runs successfully; quick-mode BMA
# estimates are deliberately too short for reporting.
QUICK_BMA <- FALSE

args_full <- commandArgs(trailingOnly = FALSE)
file_arg <- grep("^--file=", args_full, value = TRUE)
ROOT <- if (length(file_arg)) dirname(normalizePath(sub("^--file=", "", file_arg[[1]]))) else normalizePath(getwd())

TABLES <- file.path(ROOT, "tables")
FIG_PNG <- file.path(ROOT, "figures", "png")
FIG_PDF <- file.path(ROOT, "figures", "pdf")
OUTPUTS <- file.path(ROOT, "outputs")
invisible(lapply(c(TABLES, FIG_PNG, FIG_PDF, OUTPUTS), dir.create, recursive = TRUE, showWarnings = FALSE))

log_file <- file.path(OUTPUTS, "run.log")
log_connection <- file(log_file, open = "wt")
sink(log_connection, type = "output", split = TRUE)
sink(log_connection, type = "message")
on.exit({sink(type = "message"); sink(type = "output"); close(log_connection)}, add = TRUE)

started <- Sys.time()
message("Replication started: ", format(started, usetz = TRUE))

# Convert the friendly switch above into the internal setting read by the BMA
# and verification scripts. Setting it here makes one run self-contained and
# avoids requiring users to configure shell environment variables.
Sys.setenv(REPLICATION_QUICK_BMA = if (isTRUE(QUICK_BMA)) "1" else "0")
message("BMA mode: ", if (isTRUE(QUICK_BMA)) "QUICK SMOKE TEST (not for reporting)" else "FULL MANUSCRIPT SETTINGS")

# Dependency setup is deliberately part of the one-command workflow.
source(file.path(ROOT, "00_install_dependencies.R"), local = TRUE)
source(file.path(ROOT, "R", "01_data.R"), local = .GlobalEnv)

steps <- c("02_ols_and_figures.R", "03_bma.R", "04_diagnostics.R", "05_verify.R")
for (step in steps) {
  message("Running ", step, " ...")
  tryCatch(source(file.path(ROOT, "R", step), local = .GlobalEnv),
           error = function(e) stop("Step ", step, " failed: ", conditionMessage(e), call. = FALSE))
}

message("Replication completed in ", round(difftime(Sys.time(), started, units = "mins"), 2), " minutes.")
