# ---------------------------------------------------------------------------
# ex1_solution_as_written.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 1 solution as written: key and date-format checks on SDTM AE, ADSL and ADAE.
# Usage: Rscript ex1_solution_as_written.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 ex1_solution_as_written_output.txt on the workflow page (Scripts and full run).
# Packages: dplyr 1.2.1, haven 2.5.5, stringr 1.6.0, tidyr 1.3.2. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# 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
library(haven); library(dplyr); library(tidyr); library(stringr)

ae   <- read_xpt(file.path(data_dir, "sdtm_ae.xpt"))
adsl <- read_xpt(file.path(data_dir, "adam_adsl.xpt"))
adae <- read_xpt(file.path(data_dir, "adam_adae.xpt"))

stopifnot(nrow(ae) == 1191, nrow(adsl) == 254, nrow(adae) == 1191)

ae <- ae %>% arrange(USUBJID, AESEQ)

keys <- list(
  adsl_duplicate_usubjid  = adsl %>% count(USUBJID) %>% filter(n > 1) %>% nrow(),
  ae_duplicate_key        = ae %>% count(USUBJID, AESEQ) %>% filter(n > 1) %>% nrow(),
  ae_subjects_not_in_adsl = ae %>% anti_join(adsl, by = "USUBJID") %>% nrow(),
  adae_rows_not_in_ae     = adae %>% anti_join(ae, by = c("USUBJID", "AESEQ")) %>% nrow()
)
print(keys)

print(ae %>% count(length_AESTDTC = nchar(str_trim(AESTDTC))))
print(ae %>% count(length_AEENDTC = nchar(str_trim(AEENDTC))))

blanks <- ae %>%
  summarise(across(where(is.character), ~ sum(is.na(.x) | .x == ""))) %>%
  pivot_longer(everything(), names_to = "variable", values_to = "n_blank") %>%
  filter(n_blank > 0)
print(blanks)

print(sapply(adae[c("ASTDT", "AENDT", "TRTSDT", "TRTEDT")], function(x) class(x)[1]))
