# Synthetic teaching example; not OASIZ-301 participant data.
# Run from a writable folder. Output CSVs are written to the working directory.
response_summary <- function(change, threshold = 3) {
  stopifnot(is.numeric(change), length(change) > 0L,
            all(is.finite(change)), is.numeric(threshold),
            length(threshold) == 1L, is.finite(threshold), threshold > 0)
  data.frame(n = length(change), mean_change = mean(change),
             responders = sum(change <= -threshold),
             response_proportion = mean(change <= -threshold))
}

dat <- data.frame(id = sprintf("SYN-%s-%02d", rep(c("A", "B"), each = 10),
                              rep(seq_len(10), 2)),
                  group = rep(c("A", "B"), each = 10), baseline = 10,
                  change = c(rep(-4, 10), rep(-8, 5), rep(0, 5)))
dat$final <- dat$baseline + dat$change
result <- do.call(rbind, lapply(c("A", "B"), function(g) {
  data.frame(group = g, response_summary(dat$change[dat$group == g]))
}))
stopifnot(!anyDuplicated(dat$id), all(dat$final >= 0),
          identical(result$n, c(10L, 10L)),
          identical(result$mean_change, c(-4, -4)),
          identical(result$responders, c(10L, 5L)),
          identical(result$response_proportion, c(1, 0.5)),
          response_summary(c(-3, -2))$responders == 1L,
          inherits(try(response_summary(c(-4, NA_real_)), silent = TRUE), "try-error"),
          inherits(try(response_summary(c(-4, Inf)), silent = TRUE), "try-error"))
write.csv(dat, "mean-response-data.csv", row.names = FALSE)
write.csv(result, "mean-response-summary.csv", row.names = FALSE)
print(result, row.names = FALSE)
