# ---------------------------------------------------------------------------
# check_extra.R  (workflow: sas-to-r-translation)
# Reproduces: Extra checks run on top of run_fixed.R: ADUR against ADURN, flag counts, a negative control with planted errors, and the behaviour of as.Date on partial dates.
# Usage: Rscript check_extra.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: sdtm_ae.xpt; adam_adsl.xpt; adam_adae.xpt
#   Download the unmodified files from the public CDISC pilot repository:
#   https://github.com/cdisc-org/sdtm-adam-pilot-project  (folder updated-pilot-submission-package/900172/m5/)
#   (datasets as .xpt files).
# Expected output: see check_extra_output.txt on the workflow page (Scripts and full run).
# Packages: haven 2.5.5, lubridate 1.9.5. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Note: Keep run_fixed.R in the same folder. Prints R and package versions, so those lines differ between machines.
# Licence: code MIT (see README.md in the scripts folder). Data: CDISC SDTM/ADaM Pilot Project (CDISCPILOT01),
# credited to CDISC, used unmodified under the CDISC terms of use. The data are not included here.
# Logic is unchanged from the version that produced the saved output; only path handling and this header were changed.
# ---------------------------------------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."   # folder holding the CDISC pilot .xpt files
script_dir <- local({ f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
                      if (length(f)) dirname(normalizePath(f[1])) else "." })   # folder holding this script
# Extra checks written by the R specialist (NOT part of the AI's cold output).
# Re-uses the objects made by run_fixed.R, which must sit in the same folder as this script.
suppressMessages(source(file.path(script_dir, "run_fixed.R")))
cat("\n--- EXTRA CHECKS ---\n")
cat("R version:", R.version.string, "\n")
for (p in c("haven","dplyr","stringr","tibble","tidyr","lubridate","purrr","readr")) cat(p, as.character(packageVersion(p)), "\n")
cat("class of TRTSDT as read by haven::read_xpt:", class(sas$TRTSDT), "\n")
cat("class of ASTDT in SAS file after read_xpt:", class(read_xpt(file.path(data_dir, "adam_adae.xpt"))$ASTDT), "\n")
# 1. ADUR (R) vs ADURN (xpt)
cat("ADUR(R) vs ADURN(xpt): rows differing =", sum(!((is.na(adae_r$ADUR) & is.na(sas$ADURN)) | (!is.na(adae_r$ADUR) & !is.na(sas$ADURN) & adae_r$ADUR == sas$ADURN))), "\n")
# 2. ADURU: derived from ADURN in xpt
cat("ADURU values in xpt:\n"); print(table(sas$ADURU, useNA = "ifany"))
# 3. counts
cat("TRTEMFL:\n"); print(table(adae_r$TRTEMFL, useNA = "ifany"))
cat("ASTDTF D count:", sum(adae_r$ASTDTF == "D"), " ASTDT missing:", sum(is.na(adae_r$ASTDT)), " AENDT missing:", sum(is.na(adae_r$AENDT)), "\n")
for (f in c("AOCCFL","AOCCSFL","AOCCPFL","AOCC01FL","AOCC02FL","AOCC03FL","AOCC04FL")) cat(f, "Y in R:", sum(adae_r[[f]] == "Y"), " Y in xpt:", sum(trimws(sas[[f]]) == "Y"), "\n")
cat("CQ01NAM non-blank R:", sum(adae_r$CQ01NAM != ""), " xpt:", sum(trimws(sas$CQ01NAM) != ""), "\n")
# 4. row-order-independent cell count over all common columns, class of each column in R vs xpt
common <- intersect(names(sas), names(adae_r))
cells <- 0L; bad <- 0L
for (v in common) {
  a <- sas[[v]]; b <- r[[v]]
  if (is.character(a)) { a <- coalesce(str_trim(a), ""); b <- coalesce(str_trim(b), "") }
  same <- (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)
  cells <- cells + length(same); bad <- bad + sum(!same)
}
cat("cells compared:", cells, " cells differing:", bad, " columns compared:", length(common), "\n")
# 5. negative control: does the AI's comparison block detect a planted error?
r2 <- r
r2$TRTEMFL[which(r2$TRTEMFL == "N")[1:3]] <- "Y"
r2$ASTDY[5] <- r2$ASTDY[5] + 1
r2$AENDT[7] <- NA
diffs2 <- lapply(common, function(v) {
  a <- norm(sas[[v]]); b <- norm(r2[[v]])
  bad <- if (is.numeric(a) || inherits(a, "Date")) !((is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & abs(as.numeric(a) - as.numeric(b)) <= 1e-8)) else a != b
  tibble(variable = v, n_diff = sum(bad, na.rm = TRUE) + sum(is.na(bad)))
}) %>% bind_rows()
cat("negative control (3 TRTEMFL cells, 1 ASTDY cell, 1 AENDT cell planted):\n"); print(diffs2 %>% filter(n_diff > 0))
# 6. AI's key claim: naive base-R comparison gives NA
cat("naive R comparison with missing ASTDT gives:", as.character(as.Date(NA) >= as.Date("2013-01-01")), "\n")
# 7. as.Date on partial date, as bad answer claimed
cat("as.Date('2013-03') ->", tryCatch(as.character(as.Date("2013-03")), error = function(e) paste("ERROR:", conditionMessage(e))), "\n")
cat("as.Date('2013') ->", tryCatch(as.character(as.Date("2013")), error = function(e) paste("ERROR:", conditionMessage(e))), "\n")
cat("lubridate::ymd('2013-03') ->", as.character(suppressWarnings(lubridate::ymd("2013-03"))), "\n")
