# ---------------------------------------------------------------------------
# ex6_solution_as_written.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 6 solution as written: CQ01NAM and the AOCC flags rebuilt with a flag_first function and compared with ADAE.
# Usage: Rscript ex6_solution_as_written.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: 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 ex6_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)

adae <- read_xpt(file.path(data_dir, "adam_adae.xpt"))

norm <- function(x) coalesce(trimws(as.character(x)), "")

base <- adae %>%
  select(USUBJID, AESEQ, TRTEMFL, ASTDT, AESER, AEDECOD, AEBODSYS) %>%
  mutate(
    hit = str_detect(AEDECOD, fixed("APPLICATION")) |
          str_detect(AEDECOD, fixed("DERMATITIS"))  |
          str_detect(AEDECOD, fixed("ERYTHEMA"))    |
          str_detect(AEDECOD, fixed("BLISTER"))     |
          (AEBODSYS == "SKIN AND SUBCUTANEOUS TISSUE DISORDERS" &
           !(AEDECOD %in% c("COLD SWEAT", "HYPERHIDROSIS", "ALOPECIA"))),
    CQ01NAM = if_else(coalesce(hit, FALSE), "DERMATOLOGIC EVENTS", "")
  ) %>%
  select(-hit)

flag_first <- function(data, outvar, sortvars = character(), invar = NULL,
                       ser = FALSE, derm = FALSE) {
  d <- data %>% filter(TRTEMFL == "Y")
  if (!is.null(invar)) d <- d %>% filter(.data[[invar]] != "")
  if (ser)  d <- d %>% filter(AESER == "Y")
  if (derm) d <- d %>% filter(CQ01NAM == "DERMATOLOGIC EVENTS")
  d %>%
    arrange(ASTDT, AESEQ) %>%                       # ties keep AESEQ order
    group_by(across(all_of(c("USUBJID", sortvars)))) %>%
    slice(1) %>%
    ungroup() %>%
    transmute(USUBJID, AESEQ, !!outvar := "Y")
}

specs <- list(
  list(outvar = "AOCCFL",   sortvars = character(),                invar = NULL),
  list(outvar = "AOCCSFL",  sortvars = "AEBODSYS",                 invar = "AEBODSYS"),
  list(outvar = "AOCCPFL",  sortvars = c("AEBODSYS", "AEDECOD"),   invar = "AEDECOD"),
  list(outvar = "AOCC02FL", sortvars = character(),                invar = NULL, ser = TRUE),
  list(outvar = "AOCC03FL", sortvars = "AEBODSYS",                 invar = "AEBODSYS", ser = TRUE),
  list(outvar = "AOCC04FL", sortvars = c("AEBODSYS", "AEDECOD"),   invar = "AEDECOD", ser = TRUE),
  list(outvar = "AOCC01FL", sortvars = character(),                invar = NULL, derm = TRUE)
)

res <- base
for (s in specs) {
  f   <- do.call(flag_first, c(list(data = base), s))
  res <- res %>%
    left_join(f, by = c("USUBJID", "AESEQ")) %>%
    mutate(!!s$outvar := coalesce(.data[[s$outvar]], ""))
}

chk <- res %>%
  select(USUBJID, AESEQ, CQ01NAM, all_of(sapply(specs, `[[`, "outvar"))) %>%
  inner_join(adae %>% select(USUBJID, AESEQ, CQ01NAM,
                             all_of(sapply(specs, `[[`, "outvar"))),
             by = c("USUBJID", "AESEQ"), suffix = c("", ".sas"))
stopifnot(nrow(chk) == 1191)

vars <- c("CQ01NAM", sapply(specs, `[[`, "outvar"))
print(sapply(vars, function(v) sum(norm(chk[[v]]) != norm(chk[[paste0(v, ".sas")]]))))
print(sapply(vars, function(v) sum(norm(chk[[v]]) != "")))
