# FDA aggregate counts only; no individual patient data.
# Run: Rscript --vanilla voceryq-interval.R new-results-directory
if (.Platform$OS.type == "windows") invisible(Sys.setlocale("LC_CTYPE", ".UTF-8"))
args <- commandArgs(trailingOnly = TRUE)
out <- if (length(args)) args[[1]] else "voceryq-results"
if (dir.exists(out) || file.exists(out)) stop("Choose a new output directory; existing results are not overwritten.")
if (!dir.create(out, recursive = TRUE)) stop("Cannot create output directory.")
result <- stats::binom.test(7, 26, conf.level = 0.95)
estimate <- 7 / 26
ci <- unname(result$conf.int)
# Independent oracle: invert explicit binomial tail sums, not beta quantiles.
lower <- uniroot(function(p) sum(dbinom(7:26, 26, p)) - .025,
                 c(0, 1), tol = 1e-13)$root
upper <- uniroot(function(p) sum(dbinom(0:7, 26, p)) - .025,
                 c(0, 1), tol = 1e-13)$root
stopifnot(max(abs(ci - c(lower, upper))) < 1e-10,
          identical(as.integer(round(100 * ci)), c(12L, 48L)),
          abs(estimate - 0.269230769230769) < 1e-12)
summary <- data.frame(responses = 7L, efficacy_population = 26L,
                      treated_population = 32L, proportion = estimate,
                      lower95 = ci[1], upper95 = ci[2],
                      source = "FDA VOCERYQ label section 14, October 2026",
                      method = "Clopper-Pearson, descriptive aggregate audit")
write.csv(summary, file.path(out, "voceryq-summary.csv"), row.names = FALSE)
labels <- list(
 es = c("Sin cirug\u00eda durante 12 meses", "Proporci\u00f3n e IC exacto del 95%",
        "Personas de la poblaci\u00f3n de eficacia (%)",
        "Recuentos agregados FDA; rec\u00e1lculo de Algoria.",
        "Sin brazo comparador: no es una diferencia de riesgos."),
 en = c("No surgery over 12 months", "Proportion and 95% exact confidence interval",
        "People in the efficacy population (%)",
        "FDA aggregate counts; recalculation by Algoria.",
        "No comparator arm: this is not a risk difference.")
)
for (lang in names(labels)) {
 text_labels <- labels[[lang]]
 for (format in c("png", "mobile.png", "svg")) {
   path <- file.path(out, paste0("voceryq-interval.", lang, ".", format))
   if (format != "svg") png(path, width = if (format == "mobile.png") 780 else 1400,
                            height = 850, res = 160, type = "cairo")
   else svg(path, width = 8.75, height = 5.3125, family = "sans")
   par(mar = c(6.2, 1.6, 4.8, 1.2), family = "sans", fg = "#123441",
       col.axis = "#123441", col.lab = "#123441", cex = .95)
   plot(NA_real_, xlim = c(0,100), ylim = c(0,1), axes = FALSE,
        xlab = "", ylab = "", xaxs = "i")
   abline(v = seq(0,100,20), col = "#e5ecef", lwd = 1)
   segments(100*ci[1], .49, 100*ci[2], .49, col = "#0d716e", lwd = 5)
   segments(100*ci, .44, 100*ci, .54, col = "#0d716e", lwd = 2)
   points(100*estimate, .49, pch = 21, bg = "#0d716e", col = "white", cex = 2.3)
   main_number <- if (lang == "es") "7 / 26 = 26,9%" else "7 / 26 = 26.9%"
   bounds <- if (lang == "es") "IC 95%: 11,6% a 47,8%" else "95% CI: 11.6% to 47.8%"
   text(100*estimate, .82, main_number, cex = 1.55, font = 2)
   text(100*estimate, .22, bounds, cex = 1.05)
   axis(1, at = seq(0,100,20), labels = seq(0,100,20), tck = -.025)
   title(main = text_labels[1], line = 2.7, cex.main = 1.45, col.main = "#123441")
   mtext(text_labels[2], side = 3, line = 1.1, cex = 1, col = "#526773")
   mtext(text_labels[3], side = 1, line = 2.6, cex = .94)
   mtext(text_labels[4], side = 1, line = 4.0, cex = if (format == "mobile.png") .95 else .78, adj = 0)
   mtext(text_labels[5], side = 1, line = 4.9, cex = if (format == "mobile.png") .95 else .78, adj = 0)
   dev.off()
 }
}
writeLines(capture.output(sessionInfo()), file.path(out, "sessionInfo.txt"), useBytes = TRUE)
cat("PASS: independent binomial-tail oracle; tolerance 1e-10.\n")
print(summary[, 1:6])
