#!/usr/bin/env Rscript
# Recalculate percentile intervals from the bundled paired target draws.
# Run from the repository root: Rscript --vanilla tutorial/downloads/bootstrap/main-examples/summarise-draws.R charr

args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 1L || !args[1] %in% c("charr", "dogs", "red-knots")) {
  stop("Choose one example: charr, dogs or red-knots.", call. = FALSE)
}

example <- args[1]
draw_file <- if (example == "red-knots") {
  file.path("tutorial", "downloads", "extensions",
            "red-knots-intercept-bootstrap-target-draws.csv.gz")
} else file.path(
  "tutorial", "downloads", "bootstrap", "main-examples",
  paste0(example, "-target-draws.csv.gz")
)
if (!file.exists(draw_file)) stop("Run this script from the repository root.")

draws <- read.csv(gzfile(draw_file), stringsAsFactors = FALSE)
if (example == "red-knots") draws$draw <- draws$replicate
target_columns <- c("quantity", "level", "trait_1", "trait_2")
group <- do.call(paste, c(draws[target_columns], sep = "\r"))
draw_sets <- split(seq_len(nrow(draws)), group)
if (example == "red-knots") {
  retained <- unique(draws$draw)
  if (anyNA(retained) || length(draw_sets) != 69L ||
      !all(vapply(draw_sets, function(rows) {
        ids <- draws$draw[rows]
        length(ids) == length(retained) && !anyDuplicated(ids) && setequal(ids, retained)
      }, logical(1)))) stop("Missing or duplicated red-knot bootstrap targets.")
}

intervals <- lapply(draw_sets, function(rows) {
  target <- draws[rows[1], target_columns, drop = FALSE]
  limits <- stats::quantile(
    draws$value[rows], probs = c(0.025, 0.5, 0.975),
    names = FALSE, type = 7
  )
  target$lower_95 <- limits[1]
  target$median <- limits[2]
  target$upper_95 <- limits[3]
  target$paired_draws <- length(rows)
  target
})
intervals <- do.call(rbind, intervals)
rownames(intervals) <- NULL

out_dir <- file.path("analysis", "cache", "tutorial-data")
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
out_file <- file.path(out_dir, paste0(example, "-bootstrap-intervals-from-draws.csv"))
write.csv(intervals, out_file, row.names = FALSE)

cat("Recalculated", nrow(intervals), "target intervals for", example, "from",
    length(unique(draws$draw)), "paired draws.\n")
cat("Saved:", out_file, "\n")
cat("First six rows:\n")
print(utils::head(intervals))
