# ---------------------------------------------------------------------------
# ex2_solution_as_written.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 2 solution as written: derive ASTDT, AENDT and ADUR and compare with ADAE.
# Usage: Rscript ex2_solution_as_written.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: sdtm_ae.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 expected_output/ex2_output.txt in this workflow's folder.
# 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"))
adae <- read_xpt(file.path(data_dir, "adam_adae.xpt"))

same <- function(a, b) {
  a <- as.numeric(a); b <- as.numeric(b)
  (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)
}

ae2 <- ae %>%
  arrange(USUBJID, AESEQ) %>%
  mutate(
    ASTDT = as.Date(str_sub(str_trim(AESTDTC), 1, 10), format = "%Y-%m-%d"),
    AENDT = as.Date(str_sub(str_trim(AEENDTC), 1, 10), format = "%Y-%m-%d"),
    ADUR  = if_else(!is.na(ASTDT) & !is.na(AENDT),
                    as.numeric(AENDT - ASTDT) + 1, NA_real_)
  )

cmp <- ae2 %>%
  select(USUBJID, AESEQ, AESTDTC, ASTDT, AENDT, ADUR) %>%
  inner_join(adae %>% select(USUBJID, AESEQ, ASTDT_sas = ASTDT,
                             AENDT_sas = AENDT, ADURN),
             by = c("USUBJID", "AESEQ"))
stopifnot(nrow(cmp) == 1191)

result <- list(
  AENDT_mismatches = sum(!same(cmp$AENDT, cmp$AENDT_sas)),
  ASTDT_mismatches_where_derived = sum(!is.na(cmp$ASTDT) &
                                       !same(cmp$ASTDT, cmp$ASTDT_sas)),
  ASTDT_missing_here_but_present_in_ADAE = sum(is.na(cmp$ASTDT) & !is.na(cmp$ASTDT_sas)),
  ADUR_vs_ADURN_mismatches = sum(!is.na(cmp$ADUR) & !same(cmp$ADUR, cmp$ADURN))
)
print(result)
print(cmp %>% filter(is.na(ASTDT), !is.na(ASTDT_sas)) %>%
        count(length_AESTDTC = nchar(str_trim(AESTDTC))))
