rm()
# Set working directory based on the this.path package, which reliably detects the path of the running script. and projects.
if (!require(this.path)) {
  install.packages("this.path")
  require(this.path)
}
base_dir <- dirname(this.path())

# ============================================================
# Run a sequence of R scripts and report execution time
# ============================================================

files <- c(
  "01-build data base.R",
  "02-map.R",
  "03-demographic transition.R",
  "04-sibshipsize levels.R",
  "05-descendants.R",
  "06-rolling regressions.R",
  "07-wars.R",
  "08-coverage.R",
  "09-estimation.R",
  "10-macro-sim.R",
  "11-balance test.R",  
  "12-rolling regressions worldcat.R"
)

file_paths <- file.path(base_dir, files)

missing_files <- file_paths[!file.exists(file_paths)]
if (length(missing_files) > 0) {
  stop(
    "These files were not found:\n",
    paste(missing_files, collapse = "\n")
  )
}

# Path to Rscript
rscript_bin <- file.path(R.home("bin"), "Rscript.exe")
if (!file.exists(rscript_bin)) {
  rscript_bin <- "Rscript"
}

# Folder for logs
log_dir <- file.path(base_dir, "timing_logs")
dir.create(log_dir, showWarnings = FALSE)

results <- data.frame(
  file = files,
  status = NA_character_,
  elapsed_seconds = NA_real_,
  exit_status = NA_integer_,
  log_file = NA_character_,
  stringsAsFactors = FALSE
)

cat("Starting at", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n\n")

total_start <- Sys.time()

for (i in seq_along(file_paths)) {
  script_path <- normalizePath(file_paths[i], winslash = "/", mustWork = TRUE)
  script_name <- files[i]

  log_file <- file.path(
    log_dir,
    paste0(
      sprintf("%02d", i), "_",
      gsub("[^A-Za-z0-9_-]", "_", tools::file_path_sans_ext(script_name)),
      ".log"
    )
  )

  cat("--------------------------------------------------\n")
  cat("Running:", script_name, "\n")

  start_time <- Sys.time()

  exit_status <- tryCatch(
    {
      system2(
        command = rscript_bin,
        args = c("--vanilla", shQuote(script_path)),
        stdout = log_file,
        stderr = log_file,
        wait = TRUE
      )
    },
    error = function(e) {
      writeLines(
        c("Runner error:", conditionMessage(e)),
        con = log_file
      )
      NA_integer_
    }
  )

  end_time <- Sys.time()
  elapsed <- as.numeric(difftime(end_time, start_time, units = "secs"))

  results$elapsed_seconds[i] <- elapsed
  results$exit_status[i] <- exit_status
  results$log_file[i] <- log_file

  if (is.na(exit_status)) {
    results$status[i] <- "RUNNER ERROR"
  } else if (exit_status == 0) {
    results$status[i] <- "OK"
  } else {
    results$status[i] <- "ERROR"
  }

  cat("Status :", results$status[i], "\n")
  cat("Time   :", round(elapsed, 3), "seconds\n")
  cat("Log    :", log_file, "\n\n")
}

total_end <- Sys.time()
total_elapsed <- as.numeric(difftime(total_end, total_start, units = "secs"))

cat("==================================================\n")
cat("Finished at:", format(total_end, "%Y-%m-%d %H:%M:%S"), "\n")
cat("Total time :", round(total_elapsed, 3), "seconds\n\n")

print(results)

write.csv(
  results,
  file.path(base_dir, "script_timing_results.csv"),
  row.names = FALSE
)

cat("\nSaved summary to:\n")
cat(file.path(base_dir, "script_timing_results.csv"), "\n")