# Educational interval reading only. No model fitting or patient reconstruction.
# Published row: Bozkurt et al., Lancet, 2026-11-09.
# https://pubmed.ncbi.nlm.nih.gov/43003106/
# Other intervals and the 1.10 margin are invented teaching scenarios.
interpret_interval <- function(lower, upper, margin) {
  values <- c(lower, upper, margin)
  if (!is.numeric(values) || length(lower) != 1L || length(upper) != 1L ||
      length(margin) != 1L || any(!is.finite(values)) || lower <= 0 ||
      upper < lower || margin <= 1) {
    stop("Require finite scalar numbers: 0 < lower <= upper and margin > 1.")
  }
  c(non_inferiority = upper < margin, superiority_direction = upper < 1)
}

scenarios <- data.frame(
  scenario = c("published_SYNCHRONIZE_CVOT", "teaching_lower_margin",
               "teaching_both", "teaching_NI_only", "teaching_harm",
               "teaching_boundary", "teaching_inconclusive"),
  provenance = c("published_interval_and_margin", rep("teaching_only", 6)),
  lower = c(0.67, 0.67, 0.70, 0.90, 1.10, 0.90, 0.90),
  upper = c(1.18, 1.18, 0.95, 1.30, 1.30, 1.65, 1.80),
  margin = c(1.65, 1.10, 1.65, 1.65, 1.65, 1.65, 1.65)
)
decisions <- t(vapply(seq_len(nrow(scenarios)), function(i) {
  interpret_interval(scenarios$lower[i], scenarios$upper[i], scenarios$margin[i])
}, c(non_inferiority = FALSE, superiority_direction = FALSE)))
result <- cbind(scenarios, decisions)
stopifnot(identical(result$non_inferiority, c(TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE)))
stopifnot(identical(result$superiority_direction, c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE)))
stopifnot(inherits(try(interpret_interval(0, 1.18, 1.65), silent = TRUE), "try-error"))
stopifnot(inherits(try(interpret_interval(1.2, 1.18, 1.65), silent = TRUE), "try-error"))
stopifnot(inherits(try(interpret_interval(NA_real_, 1.18, 1.65), silent = TRUE), "try-error"))
stopifnot(inherits(try(interpret_interval(0.67, Inf, 1.65), silent = TRUE), "try-error"))
stopifnot(inherits(try(interpret_interval(c(0.6, 0.7), 1.18, 1.65), silent = TRUE), "try-error"))
stopifnot(inherits(try(interpret_interval(0.67, 1.18, 1), silent = TRUE), "try-error"))
print(result, row.names = FALSE)
write.csv(result, "interval-exercise.csv", row.names = FALSE)
cat("Checks passed. Output: interval-exercise.csv\n")
