# ---------------------------------------------------------------------------
# ex3_solution_as_written.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 3 solution as written: merge with ADSL, impute partial start dates, derive ASTDY, AENDY and TRTEMFL, and compare with ADAE.
# Usage: Rscript ex3_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 expected_output/ex3_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"))
adsl <- read_xpt(file.path(data_dir, "adam_adsl.xpt"))
adae <- read_xpt(file.path(data_dir, "adam_adae.xpt"))

norm <- function(x) if (is.character(x)) coalesce(trimws(x), "") else as.numeric(x)
same <- function(a, b) {
  a <- norm(a); b <- norm(b)
  (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)
}

temp <- adsl %>%
  select(SITEID, USUBJID, TRTA = TRT01A, TRTAN = TRT01AN, AGE, AGEGR1, AGEGR1N,
         RACE, RACEN, SEX, SAFFL, TRTSDT, TRTEDT)
stopifnot(!anyDuplicated(temp$USUBJID))   # many-to-one, like the SAS merge

teae <- ae %>%
  arrange(USUBJID, AESEQ) %>%
  mutate(
    sdtc  = str_trim(AESTDTC),
    ASTDT = as.Date(str_sub(sdtc, 1, 10), format = "%Y-%m-%d"),
    AENDT = as.Date(str_sub(str_trim(AEENDTC), 1, 10), format = "%Y-%m-%d")
  ) %>%
  left_join(temp, by = "USUBJID") %>%
  mutate(
    partial = is.na(ASTDT) & coalesce(nchar(sdtc) == 7, FALSE),
    ASTDT   = if_else(partial,
                      as.Date(str_c(sdtc, "-01"), format = "%Y-%m-%d"), ASTDT),
    ASTDTF  = if_else(partial, "D", ""),
    ASTDY = case_when(
      !is.na(ASTDT) & !is.na(TRTSDT) & ASTDT >= TRTSDT ~ as.numeric(ASTDT - TRTSDT) + 1,
      !is.na(ASTDT) & !is.na(TRTSDT) & TRTSDT > ASTDT  ~ as.numeric(ASTDT - TRTSDT),
      .default = NA_real_),
    AENDY = case_when(
      !is.na(AENDT) & !is.na(TRTSDT) & AENDT >= TRTSDT ~ as.numeric(AENDT - TRTSDT) + 1,
      !is.na(AENDT) & !is.na(TRTSDT) & TRTSDT > AENDT  ~ as.numeric(AENDT - TRTSDT),
      .default = NA_real_),
    TRTEMFL = if_else(!is.na(ASTDT) & !is.na(TRTSDT) & ASTDT >= TRTSDT, "Y", "N")
  )

cols <- c("SITEID", "TRTA", "TRTAN", "AGE", "AGEGR1", "AGEGR1N", "RACE", "RACEN",
          "SEX", "SAFFL", "TRTSDT", "TRTEDT", "ASTDT", "ASTDTF", "ASTDY",
          "AENDT", "AENDY", "TRTEMFL")

chk <- teae %>%
  select(USUBJID, AESEQ, all_of(cols)) %>%
  inner_join(adae %>% select(USUBJID, AESEQ, all_of(cols)),
             by = c("USUBJID", "AESEQ"), suffix = c("", ".sas"))
stopifnot(nrow(teae) == 1191, nrow(chk) == 1191)

mismatches <- sapply(cols, function(v) sum(!same(chk[[v]], chk[[paste0(v, ".sas")]])))
print(mismatches)
print(count(teae, ASTDTF, TRTEMFL))
