# ---------------------------------------------------------------------------
# checks.R  (workflow: submission-program-readiness-review)
# Reproduces: Evidence checks C0 to C10 for the line-cited review of adam_adae.sas: ADUR versus ADURN, partial dates, the missing upper bound on TRTEMFL, the CQ01NAM rule, first-occurrence ties, and more.
# Usage: Rscript checks.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; adam_adae.sas
#   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; adam_adae.sas is in the ADaM programs folder).
# Expected output: see expected_output/checks_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5, stringr 1.6.0. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Note: Needs cq01_list.R in the same folder.
# 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
# Evidence checks for the line-cited review of adam_adae.sas (CDISCPILOT01). Real xpt files, read-only, nothing modified.
suppressMessages({library(haven);library(dplyr);library(stringr)})
src <- paste0(sub("/+$", "", data_dir), "/")
ae <- read_xpt(paste0(src,"sdtm_ae.xpt")); adae <- read_xpt(paste0(src,"adam_adae.xpt")); adsl <- read_xpt(paste0(src,"adam_adsl.xpt"))
sas_lines <- readLines(paste0(src,"adam_adae.sas"), warn=FALSE)
cat("== C0 file read: adam_adae.sas has", length(sas_lines), "lines; ae rows", nrow(ae), "; adae rows", nrow(adae), "; adsl rows", nrow(adsl), "\n")

cat("\n== C1 (line 15, 120, 125, 131): program creates ADUR; delivered xpt has ADURN and ADURU instead\n")
cat("   only in xpt:", setdiff(names(adae), c(
 "STUDYID","SITEID","USUBJID","TRTA","TRTAN","AGE","AGEGR1","AGEGR1N","RACE","RACEN","SEX","SAFFL","TRTSDT","TRTEDT","ASTDT","ASTDTF","ASTDY","AENDT","AENDY","ADUR","AETERM","AELLT","AELLTCD","AEDECOD","AEPTCD","AEHLT","AEHLTCD","AEHLGT","AEHLGTCD","AEBODSYS","AESOC","AESOCCD","AESEV","AESER","AESCAN","AESCONG","AESDISAB","AESDTH","AESHOSP","AESLIFE","AESOD","AEREL","AEACN","AEOUT","AESEQ","TRTEMFL","AOCCFL","AOCCSFL","AOCCPFL","AOCC02FL","AOCC03FL","AOCC04FL","CQ01NAM","AOCC01FL")), "\n")
cat("   program's retain list (lines 124-127) has 55 names incl. ADUR; xpt has", ncol(adae), "columns; ADUR in xpt:", "ADUR" %in% names(adae), "\n")
cat("   label of ADURN in xpt:", attr(adae$ADURN,"label"), "| label given in program line 120: AE Duration (days)\n")

cat("\n== C2 (lines 13-14, 28-31, 40-41): partial start dates\n")
n <- nchar(trimws(ae$AESTDTC)); cat("   AESTDTC length 4 (year only):", sum(n==4), " length 7 (YYYY-MM):", sum(n==7), " length 10:", sum(n==10), "\n")
cat("   ASTDT missing after the program ran:", sum(is.na(adae$ASTDT)), " of which TRTEMFL='N':", sum(is.na(adae$ASTDT) & adae$TRTEMFL=="N"), "\n")
yo <- adae %>% filter(is.na(ASTDT)) %>% left_join(ae %>% select(USUBJID,AESEQ,AESTDTC), by=c("USUBJID","AESEQ"))
cat("   year-only start year vs TRT start year (rows where the year equals the treatment-start year):", sum(as.integer(trimws(yo$AESTDTC)) == as.integer(format(yo$TRTSDT,"%Y"))), "of", nrow(yo), "\n")
mo <- adae %>% filter(ASTDTF=="D") %>% left_join(ae %>% select(USUBJID,AESEQ,AESTDTC), by=c("USUBJID","AESEQ"))
cat("   month-only starts imputed to day 01:", nrow(mo), "; of these in the SAME month as TRTSDT:", sum(substr(mo$AESTDTC,1,7) == format(mo$TRTSDT,"%Y-%m")), "\n")
cat("   month-only starts with TRTEMFL='Y':", sum(mo$TRTEMFL=="Y"), " 'N':", sum(mo$TRTEMFL=="N"), "\n")
cat("   AEENDTC blank (never imputed, so AENDT/AENDY/ADUR missing):", sum(trimws(ae$AEENDTC)==""), " of ", nrow(ae), "\n")

cat("\n== C3 (line 40): TRTEMFL has no upper bound\n")
y <- adae %>% filter(TRTEMFL=="Y", !is.na(ASTDT), ASTDT > TRTEDT)
cat("   TRTEMFL='Y' with ASTDT after TRTEDT:", nrow(y), "; largest gap (days):", max(as.numeric(y$ASTDT - y$TRTEDT)), "\n")
cat("   TRTEMFL counts:\n"); print(table(adae$TRTEMFL))
cat("   rows with TRTEMFL='N' and a non-missing ASTDT before TRTSDT:", sum(adae$TRTEMFL=="N" & !is.na(adae$ASTDT)), "\n")

cat("\n== C4 (lines 42-47): CQ01NAM; see cq01_vs_csr.R for the comparison with CSR Table 12-2\n")
cat("   lower-case letters in AEDECOD/AEBODSYS (index() and = are case-sensitive):", sum(str_detect(adae$AEDECOD,"[a-z]")), sum(str_detect(adae$AEBODSYS,"[a-z]")), "\n")
sk <- adae %>% filter(AEBODSYS=="SKIN AND SUBCUTANEOUS TISSUE DISORDERS", trimws(CQ01NAM)=="")
cat("   skin-SOC rows excluded by the hard-coded list in line 46:", nrow(sk), " (", paste(names(table(sk$AEDECOD)), table(sk$AEDECOD), collapse=", "), ")\n")

cat("\n== C5 (lines 56-57, 65-68): first-occurrence ties. SAS PROC SORT keeps input order within ties (EQUALS), input order is AESEQ\n")
first_flag <- function(d, tie = c("aeseq","reverse")) {
  tie <- match.arg(tie)
  d <- d %>% filter(TRTEMFL=="Y")
  d <- if (tie=="aeseq") d %>% arrange(USUBJID, ASTDT, AESEQ) else d %>% arrange(USUBJID, ASTDT, desc(AESEQ))
  d %>% group_by(USUBJID) %>% slice_head(n=1) %>% ungroup() %>% transmute(USUBJID, AESEQ)
}
a <- first_flag(adae,"aeseq"); b <- first_flag(adae,"reverse")
cat("   AOCCFL='Y' in xpt:", sum(trimws(adae$AOCCFL)=="Y"), " ; rows equal to the AESEQ tie-break:", sum(paste(a$USUBJID,a$AESEQ) %in% paste(adae$USUBJID[trimws(adae$AOCCFL)=="Y"], adae$AESEQ[trimws(adae$AOCCFL)=="Y"])),
    " ; rows equal to a reverse tie-break:", sum(paste(b$USUBJID,b$AESEQ) %in% paste(adae$USUBJID[trimws(adae$AOCCFL)=="Y"], adae$AESEQ[trimws(adae$AOCCFL)=="Y"])), "\n")

cat("\n== C6 (lines 19-20, 25-27): ADSL key and SAFFL\n")
cat("   ADSL USUBJID unique:", !anyDuplicated(adsl$USUBJID), "; AE subjects missing from ADSL:", sum(!ae$USUBJID %in% adsl$USUBJID), "; SAFFL values in ADAE:", paste(names(table(adae$SAFFL)),collapse=","), "\n")

cat("\n== C7 (line 37): ANLSTDY is derived and never kept\n   ANLSTDY in xpt:", "ANLSTDY" %in% names(adae), "\n")

cat("\n== C8: text checks on the .sas file (lines are 1-based)\n")
cm <- grep("^[[:space:]]*[*][^%]|^[[:space:]]*/[*]|[*]/[[:space:]]*$", sas_lines); cat("   lines starting a * comment or touching a /* */ comment:", length(cm), "of", length(sas_lines), "
")
cat("   hard-coded Windows paths on lines:", grep("[A-Z]:\\\\", sas_lines), "\n")
cat("   'endsas;' on line:", grep("^[[:space:]]*endsas", sas_lines), "\n")
cat("   upper-case character literals in the CQ rule (line 42-47):", paste(unlist(str_extract_all(paste(sas_lines[42:47],collapse=" "), "'[^']+'")), collapse=" | "), "\n")

cat("\n== C9 (lines 81-82, 96-97): PT under more than one SOC; keys unique in SDTM AE\n")
pt_soc <- adae %>% distinct(AEDECOD, AEBODSYS) %>% count(AEDECOD) %>% filter(n > 1)
cat("   PTs appearing under more than one SOC in ADAE:", nrow(pt_soc), "\n")
cat("   SDTM AE (USUBJID, AESEQ) duplicated rows:", sum(duplicated(ae[c("USUBJID","AESEQ")])), "\n")

cat("\n== C10 (lines 42-47, 90): effect of the CQ01 rule on AOCC01FL, compared with the PT list in CSR Table 12-2\n")
source(file.path(script_dir, "cq01_list.R"))
d <- adae %>% filter(TRTEMFL=="Y", AEDECOD %in% t122) %>% arrange(USUBJID, ASTDT, AESEQ) %>% group_by(USUBJID) %>% slice_head(n=1) %>% ungroup()
key_csr <- paste(d$USUBJID, d$AESEQ); key_xpt <- paste(adae$USUBJID, adae$AESEQ)[trimws(adae$AOCC01FL)=="Y"]
cat("   subjects with a first TE dermatologic event: xpt AOCC01FL =", length(key_xpt), "; using the CSR Table 12-2 list =", length(key_csr), "\n")
cat("   AOCC01FL='Y' records that differ between the two:", length(setdiff(key_xpt, key_csr)) + length(setdiff(key_csr, key_xpt)), "\n")
cat("   subjects with any CQ01 row but none in the CSR list:", length(setdiff(unique(adae$USUBJID[trimws(adae$CQ01NAM)!=""]), unique(adae$USUBJID[adae$AEDECOD %in% t122]))), "\n")
