# Independent recomputation of every number in the AI summary (good_output.txt).
# Usage: Rscript recompute.R <folder with adam_adsl.xpt, adam_adae.xpt> <path to good_output.txt>
# Data: CDISC SDTM/ADaM Pilot Project, used unmodified, attribution to CDISC.
# Written separately from dsmb_inputs.R (base R tabulation, ADSL-driven denominators, own rounding).
args <- commandArgs(TRUE)
# Needs the R packages haven and dplyr (install.packages(c("haven","dplyr")) if missing).
suppressMessages(library(haven))
adsl <- read_xpt(file.path(args[1], "adam_adsl.xpt"))
adae <- read_xpt(file.path(args[1], "adam_adae.xpt"))
txt  <- paste(readLines(args[2], warn = FALSE), collapse = "\n")

arms <- c("Placebo", "Xanomeline Low Dose", "Xanomeline High Dose")
saf  <- adsl[adsl$SAFFL == "Y", ]
N    <- sapply(arms, function(a) sum(saf$TRT01A == a))
te   <- adae[adae$SAFFL == "Y" & adae$TRTEMFL == "Y", ]
# round half up to 1 decimal (SAS style)
r1   <- function(x) floor(x * 10 + 0.5 + 1e-9) / 10
npct <- function(n, d) sprintf("%d (%.1f%%)", n, r1(100 * n / d))

nsub <- function(rows, ids = rows$USUBJID, arm = rows$TRTA)
  sapply(arms, function(a) length(unique(ids[arm == a])))

res <- list()   # label -> list(recomputed = c(...), ai = c(...))
add <- function(label, rec, ai) res[[label]] <<- list(rec = rec, ai = ai)

# Table 3.1 rows: AI text value per arm (typed from good_output.txt, then also searched for in the text)
add("Any TEAE",            npct(nsub(te), N),                                  c("65 (75.6%)","77 (91.7%)","76 (90.5%)"))
add("Total TEAE events",   as.character(sapply(arms, function(a) sum(te$TRTA == a))), c("281","412","433"))
add("Any serious TEAE",    npct(nsub(te[te$AESER == "Y", ]), N),               c("0 (0.0%)","1 (1.2%)","2 (2.4%)"))
add("Any severe TEAE",     npct(nsub(te[te$AESEV == "SEVERE", ]), N),          c("5 (5.8%)","16 (19.0%)","8 (9.5%)"))
add("POSSIBLE/PROBABLE related TEAE", npct(nsub(te[te$AEREL %in% c("POSSIBLE","PROBABLE"), ]), N), c("43 (50.0%)","72 (85.7%)","70 (83.3%)"))
ae_dc <- saf[saf$DCDECOD == "ADVERSE EVENT", ]
add("Discontinued, reason AE (ADSL)", npct(nsub(ae_dc, ae_dc$USUBJID, ae_dc$TRT01A), N), c("8 (9.3%)","44 (52.4%)","40 (47.6%)"))
dth <- saf[which(saf$DTHFL == "Y"), ]
add("Deaths (DTHFL = Y)",  npct(nsub(dth, dth$USUBJID, dth$TRT01A), N),        c("2 (2.3%)","1 (1.2%)","0 (0.0%)"))

# Derived numbers in the AI text
pc  <- sapply(arms, function(a) 100 * length(unique(te$USUBJID[te$TRTA == a])) / N[a])
ev  <- sapply(arms, function(a) sum(te$TRTA == a))
add("Diff vs placebo, Low (91.7 - 75.6)",  sprintf("%.1f", r1(pc[2]) - r1(pc[1])), "16.1")
add("Diff vs placebo, High (90.5 - 75.6)", sprintf("%.1f", r1(pc[3]) - r1(pc[1])), "14.9")
add("Unrounded diff Low / High (information)", sprintf("%.1f / %.1f", pc[2]-pc[1], pc[3]-pc[1]), "16.1 / 14.9")
add("Events per subject",  sprintf("%.2f", ev / N),                            c("3.27","4.90","5.15"))
add("Serious TEAE total",  as.character(length(unique(te$USUBJID[te$AESER == "Y"]))), "3")
add("AE discontinuation total", as.character(nrow(ae_dc)),                     "92")
add("Death total",         as.character(nrow(dth)),                            "3")
add("Safety N",            as.character(N),                                    c("86","84","84"))

# Table 3.2 rows
pts <- c("PRURITUS","APPLICATION SITE PRURITUS","APPLICATION SITE ERYTHEMA","ERYTHEMA","DIZZINESS",
         "APPLICATION SITE IRRITATION","RASH","APPLICATION SITE DERMATITIS")
ai32 <- list(PRURITUS=c("8 (9.3%)","21 (25.0%)","26 (31.0%)"),
  "APPLICATION SITE PRURITUS"=c("6 (7.0%)","22 (26.2%)","22 (26.2%)"),
  "APPLICATION SITE ERYTHEMA"=c("3 (3.5%)","12 (14.3%)","15 (17.9%)"),
  ERYTHEMA=c("8 (9.3%)","14 (16.7%)","14 (16.7%)"),
  DIZZINESS=c("2 (2.3%)","8 (9.5%)","11 (13.1%)"),
  "APPLICATION SITE IRRITATION"=c("3 (3.5%)","9 (10.7%)","9 (10.7%)"),
  RASH=c("5 (5.8%)","13 (15.5%)","9 (10.7%)"),
  "APPLICATION SITE DERMATITIS"=c("5 (5.8%)","9 (10.7%)","7 (8.3%)"))
for (p in pts) add(paste("PT:", p), npct(nsub(te[te$AEDECOD == p, ]), N), ai32[[p]])

# Is Table 3.2 the complete set meeting its stated rule? (rule: >=10% in either xanomeline arm, higher than placebo in both)
allpt <- sort(unique(te$AEDECOD))
pct   <- sapply(allpt, function(p) sapply(arms, function(a) length(unique(te$USUBJID[te$AEDECOD == p & te$TRTA == a])) / N[a]))
keep  <- allpt[(pct[2, ] >= .10 | pct[3, ] >= .10) & pct[2, ] > pct[1, ] & pct[3, ] > pct[1, ]]
add("Table 3.2 term set equals stated rule", ifelse(setequal(keep, pts), "TRUE", paste("FALSE; rule gives:", paste(keep, collapse = "; "))), "TRUE")

# Listing 3.3 and 3.4 facts
sae <- te[te$AESER == "Y", ]
add("Serious TEAE listing (USUBJID|PT|AESEV|AEREL|day)",
    sort(paste(sae$USUBJID, sae$AEDECOD, sae$AESEV, sae$AEREL, sae$ASTDY, sep = "|")),
    sort(c("01-709-1424|SYNCOPE|MODERATE|POSSIBLE|5","01-718-1170|SYNCOPE|SEVERE|PROBABLE|27",
           "01-718-1371|PARTIAL SEIZURES WITH SECONDARY GENERALISATION|SEVERE|NONE|38")))
add("Deaths listing (USUBJID|arm)", sort(paste(dth$USUBJID, dth$TRT01A, sep = "|")),
    sort(c("01-701-1211|Xanomeline Low Dose","01-704-1445|Placebo","01-710-1083|Placebo")))
add("Deaths with any serious AE record in ADAE", as.character(sum(adae$USUBJID %in% dth$USUBJID & adae$AESER == "Y")), "0")
add("AEACN non-missing records", as.character(sum(!is.na(adae$AEACN) & trimws(adae$AEACN) != "")), "0")

# Compare, and also confirm that the AI strings actually occur in the saved output text
ok <- 0; bad <- 0
for (lab in names(res)) {
  rec <- as.character(res[[lab]]$rec); ai <- as.character(res[[lab]]$ai)
  same <- identical(unname(rec), unname(ai))
  intext <- all(vapply(ai, function(s) grepl(s, txt, fixed = TRUE), logical(1))) || grepl("listing|Listing|Unrounded|set equals|non-missing|serious AE record", lab)
  status <- if (same && intext) "MATCH   " else "MISMATCH"
  if (same && intext) ok <- ok + 1 else bad <- bad + 1
  cat(sprintf("%s %-55s recomputed=[%s]  AI=[%s]%s\n", status, lab, paste(rec, collapse=" | "), paste(ai, collapse=" | "),
              if (!intext) "  (AI string not found in output text)" else ""))
}
cat(sprintf("\n%d of %d checks match, %d mismatch.\n", ok, ok + bad, bad))

# Cross-checks against the CSR (typed from cdiscpilot01_csr.pdf; see VERIFICATION_REPORT)
cat("\nCSR cross-checks (typed from the CSR):\n")
cat("  Table 14-5.01 ANY BODY SYSTEM: 65 (75.6%) [281], 77 (91.7%) [412], 76 (90.5%) [433]  -> recomputed:",
    paste(npct(nsub(te), N), ev, collapse = "; "), "\n")
cat("  Table 14-5.02 ANY BODY SYSTEM serious: 0, 1 (1.2%), 2 (2.4%)  -> recomputed:", paste(npct(nsub(sae), N), collapse = "; "), "\n")
cat("  CSR Section 12.3.1: 3 deaths, 2 placebo, 1 low dose  -> recomputed:", paste(nsub(dth, dth$USUBJID, dth$TRT01A), collapse = "/"), "\n")
early <- saf[saf$DCDECOD == "ADVERSE EVENT" & saf$COMP24FL != "Y", ]
cat("  CSR Table 14-1.02 AE reason, early termination prior to Week 24: 8 / 44 / 39 -> recomputed (DCDECOD = AE and COMP24FL != Y):",
    paste(nsub(early, early$USUBJID, early$TRT01A), collapse = " / "), "\n")
cat("  The AI table value 40 for High Dose counts any-time AE discontinuation (includes 1 subject with COMP24FL = Y): ",
    paste(early$USUBJID[0], "", collapse = ""), paste(saf$USUBJID[saf$DCDECOD == "ADVERSE EVENT" & saf$COMP24FL == "Y"], collapse = ","), "\n")
