# ---------------------------------------------------------------------------
# recompute_table_14-2.01.R  (workflow: output-qc-ai-code)
# Reproduces: recomputes CSR Table 14-2.01 (CDISCPILOT01, ITT population) from adam_adsl.xpt and compares
#   every cell to the CSR values: 96 cells (Age, Age group, Sex, Race, Baseline weight, Baseline BMI group).
# Usage:  Rscript recompute_table_14-2.01.R <data_dir> [out_dir]
#   data_dir = folder containing adam_adsl.xpt (default: current folder).
#   out_dir  = where match_table_14-2.01.csv is written (default: current folder).
# Input:  adam_adsl.xpt, unmodified, from https://github.com/cdisc-org/sdtm-adam-pilot-project
#   (updated-pilot-submission-package/900172/m5/). Credited to CDISC; used under the CDISC terms of use.
# Answer key: CSR Table 14-2.01, PDF pages 46 to 48 (cdiscpilot01_csr.pdf), typed into the csr list below.
#   Check it against the CSR yourself: a typo in the key shows up as a false MISMATCH.
# Packages: haven, dplyr. Tested with R 4.6.1 on Windows.
# Not covered: p-value column and the MMSE, duration of disease, education and height rows.
# Origin: written by Claude on 2026-10-22 from the short prompt on the workflow page (cold run, nothing executed
#   by the model). Reply 1 covered 80 cells and declined the 16 Race cells as not derivable. The Race block
#   below came from reply 2, after the reader supplied the rule "Hispanic ethnicity takes precedence over race".
#   That rule is inferred from the counts; it is not written in the CSR or define.xml. Confirm it against the SAP
#   or the production program.
# Logic is as the model wrote it. Only this header, path handling and the CSV writer were added.
# Licence: code MIT. Data not included.
# ---------------------------------------------------------------------------
library(haven)
library(dplyr)

args <- commandArgs(TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."
out_dir  <- if (length(args) >= 2) args[2] else "."
adsl <- read_xpt(file.path(data_dir, "adam_adsl.xpt")) %>% filter(ITTFL == "Y")

trts <- c("Placebo", "Xanomeline Low Dose", "Xanomeline High Dose")
cols <- c(lapply(trts, function(t) adsl %>% filter(TRT01P == t)),
          list(adsl))
names(cols) <- c(trts, "Total")
Ncol <- sapply(cols, nrow)

# Round half up (avoids R's round-half-even and float error)
rhu <- function(x, d) floor(x * 10^d + 0.5 + 1e-9) / 10^d
fnum <- function(x, d) sprintf(paste0("%.", d, "f"), rhu(x, d))

fcnt <- function(n, N) {
  if (n == 0) return("0")
  p <- 100 * n / N
  s <- if (p < 1) "<1%" else sprintf("%d%%", as.integer(floor(p + 0.5 + 1e-9)))
  paste0(n, " (", s, ")")
}

# ---- CSR values (order: Placebo, Low, High, Total) ----
csr <- list(
  "Age n"      = c("86","84","84","254"),
  "Age Mean"   = c("75.2","75.7","74.4","75.1"),
  "Age SD"     = c("8.59","8.29","7.89","8.25"),
  "Age Median" = c("76.0","77.5","76.0","77.0"),
  "Age Min"    = c("52.0","51.0","56.0","51.0"),
  "Age Max"    = c("89.0","88.0","88.0","89.0"),
  "AGEGR1 <65"   = c("14 (16%)","8 (10%)","11 (13%)","33 (13%)"),
  "AGEGR1 65-80" = c("42 (49%)","47 (56%)","55 (65%)","144 (57%)"),
  "AGEGR1 >80"   = c("30 (35%)","29 (35%)","18 (21%)","77 (30%)"),
  "Sex M" = c("33 (38%)","34 (40%)","44 (52%)","111 (44%)"),
  "Sex F" = c("53 (62%)","50 (60%)","40 (48%)","143 (56%)"),
  "Weight n"      = c("86","83","84","253"),
  "Weight Mean"   = c("62.8","67.3","70.0","66.6"),
  "Weight SD"     = c("12.77","14.12","14.65","14.13"),
  "Weight Median" = c("60.6","64.9","69.2","66.7"),
  "Weight Min"    = c("34.0","45.4","41.7","34.0"),
  "Weight Max"    = c("86.2","106.1","108.0","108.0"),
  "BMI <25"   = c("59 (69%)","47 (56%)","44 (52%)","150 (59%)"),
  "BMI 25-<30"= c("21 (24%)","27 (32%)","28 (33%)","76 (30%)"),
  "BMI >=30"  = c("6 (7%)","10 (12%)","12 (14%)","28 (11%)")
)


# ---- Reply 2: Race (Origin) block, ethnicity takes precedence (rule supplied by the reader) ----
csr <- c(csr, list(
  "Race Caucasian"       = c("75 (87%)","72 (86%)","71 (85%)","218 (86%)"),
  "Race African Descent" = c("8 (9%)","6 (7%)","9 (11%)","23 (9%)"),
  "Race Hispanic"        = c("3 (3%)","6 (7%)","3 (4%)","12 (5%)"),
  "Race Other"           = c("0","0","1 (1%)","1 (<1%)")
))
race_grp <- function(d) {
  r <- toupper(trimws(as.character(d$RACE)))
  e <- toupper(trimws(as.character(d$ETHNIC)))
  case_when(
    !is.na(e) & e == "HISPANIC OR LATINO"          ~ "Hispanic",      # ethnicity takes precedence
    !is.na(r) & r == "WHITE"                       ~ "Caucasian",
    !is.na(r) & r == "BLACK OR AFRICAN AMERICAN"   ~ "African Descent",
    TRUE                                           ~ "Other"          # all remaining RACE values, including missing
  )
}

# ---- Recompute from ADSL ----
cont <- function(x, d_mean, d_sd, d_med) {
  x <- x[!is.na(x)]
  c(n = as.character(length(x)), Mean = fnum(mean(x), d_mean),
    SD = fnum(sd(x), d_sd), Median = fnum(median(x), d_med),
    Min = fnum(min(x), 1), Max = fnum(max(x), 1))
}
cnt <- function(d, var, val, N) fcnt(sum(d[[var]] == val, na.rm = TRUE), N)

derived <- list()
for (k in seq_along(cols)) {
  d <- cols[[k]]; N <- Ncol[k]
  d$RACEGRP <- race_grp(d)
  derived[["Race Caucasian"]][k]       <- cnt(d, "RACEGRP", "Caucasian", N)
  derived[["Race African Descent"]][k] <- cnt(d, "RACEGRP", "African Descent", N)
  derived[["Race Hispanic"]][k]        <- cnt(d, "RACEGRP", "Hispanic", N)
  derived[["Race Other"]][k]           <- cnt(d, "RACEGRP", "Other", N)
  a <- cont(d$AGE, 1, 2, 1)
  w <- cont(d$WEIGHTBL, 1, 2, 1)
  derived[["Age n"]][k] <- a["n"];      derived[["Age Mean"]][k] <- a["Mean"]
  derived[["Age SD"]][k] <- a["SD"];    derived[["Age Median"]][k] <- a["Median"]
  derived[["Age Min"]][k] <- a["Min"];  derived[["Age Max"]][k] <- a["Max"]
  derived[["AGEGR1 <65"]][k]   <- cnt(d, "AGEGR1", "<65", N)
  derived[["AGEGR1 65-80"]][k] <- cnt(d, "AGEGR1", "65-80", N)
  derived[["AGEGR1 >80"]][k]   <- cnt(d, "AGEGR1", ">80", N)
  derived[["Sex M"]][k] <- cnt(d, "SEX", "M", N)
  derived[["Sex F"]][k] <- cnt(d, "SEX", "F", N)
  derived[["Weight n"]][k] <- w["n"];      derived[["Weight Mean"]][k] <- w["Mean"]
  derived[["Weight SD"]][k] <- w["SD"];    derived[["Weight Median"]][k] <- w["Median"]
  derived[["Weight Min"]][k] <- w["Min"];  derived[["Weight Max"]][k] <- w["Max"]
  derived[["BMI <25"]][k]    <- cnt(d, "BMIBLGR1", "<25", N)
  derived[["BMI 25-<30"]][k] <- cnt(d, "BMIBLGR1", "25-<30", N)
  derived[["BMI >=30"]][k]   <- cnt(d, "BMIBLGR1", ">=30", N)
}

# ---- Check N headers, then every cell ----
cat("Column N check (CSR: 86, 84, 84, 254):", paste(Ncol, collapse = ", "), "\n\n")
matched <- 0; total <- 0; tab <- list()
for (row in names(csr)) {
  for (k in seq_along(cols)) {
    total <- total + 1
    ok <- identical(unname(derived[[row]][k]), csr[[row]][k])
    if (ok) matched <- matched + 1
    tab[[length(tab) + 1]] <- data.frame(row = row, column = names(cols)[k], csr = csr[[row]][k],
                                         recomputed = derived[[row]][k], result = ifelse(ok, "MATCH", "MISMATCH"))
    cat(sprintf("%-15s %-22s CSR=%-10s ADSL=%-10s %s\n", row, names(cols)[k],
                csr[[row]][k], derived[[row]][k], ifelse(ok, "MATCH", "MISMATCH")))
  }
}
cat(sprintf("\n%d of %d checked cells matched.\n", matched, total))

write.csv(do.call(rbind, tab), file.path(out_dir, "match_table_14-2.01.csv"), row.names = FALSE)
cat("
Distinct RACE values in the data, for review:
")
print(table(adsl$RACE, useNA = "ifany"))
cat("
Distinct ETHNIC values in the data, for review:
")
print(table(adsl$ETHNIC, useNA = "ifany"))
