# ---------------------------------------------------------------------------
# run_fixed.R  (workflow: sas-to-r-translation)
# Reproduces: The same translation with the one-line fix (helper renamed to aedecod_trim), then a cell-by-cell comparison with the SAS-produced adam_adae.xpt. Expect zero differing variables.
# Usage: Rscript run_fixed.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/run_fixed_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.
# 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(dplyr)
library(stringr)
library(haven)

# SAS dates are days since 1960-01-01, R Dates are days since 1970-01-01.
# Different behaviour: haven may or may not turn a SAS date column into an R Date
# depending on the format stored in the xpt. This helper handles both. [not checked against the file]
to_date <- function(x) if (inherits(x, "Date")) x else as.Date(x, origin = "1960-01-01")

# SAS: input(strip(x), ?? yymmdd10.)  reads the first 10 characters; a partial date such as
# "2013-12" or any invalid string gives a missing value and ?? hides the log message.
# R: as.Date() with an explicit format also gives NA for invalid input. I add a strict
# pattern so "2013-1-5" style strings are not silently accepted. yymmdd10. is more
# permissive than this (it also reads 20131226). [assumption: the data hold ISO 8601 only]
parse_ymd10 <- function(x) {
  s <- substr(str_trim(x), 1, 10)
  ok <- !is.na(s) & str_detect(s, "^\\d{4}-\\d{2}-\\d{2}$")
  out <- as.Date(rep(NA_character_, length(s)))
  out[ok] <- as.Date(s[ok], format = "%Y-%m-%d")
  out
}

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

# Step 1: proc sort by USUBJID AESEQ.
# SAS PROC SORT is stable (EQUALS); dplyr::arrange is stable too. Missing sorts first in SAS,
# and arrange puts NA last, but neither key has missing values here. [assumption]
# Character sort order: SAS uses the host collating sequence, dplyr 1.1+ uses the C locale. Same for ASCII IDs.
ae <- ae %>% arrange(USUBJID, AESEQ)

# Step 2: first data step. ADUR is computed BEFORE the partial-date imputation below,
# so ADUR stays missing when the start date is partial. I keep that order on purpose.
# SAS: ASTDT>.z is "not missing". R: use is.na().
ae <- ae %>%
  mutate(
    ASTDT = parse_ymd10(AESTDTC),
    AENDT = parse_ymd10(AEENDTC),
    ADUR  = if_else(!is.na(ASTDT) & !is.na(AENDT), as.numeric(AENDT - ASTDT) + 1, NA_real_)
  )

# Step 3: TEMP = ADSL subset, renamed.
temp <- adsl %>%
  select(SITEID, USUBJID, TRT01A, TRT01AN, AGE, AGEGR1, AGEGR1N, RACE, RACEN, SEX, SAFFL, TRTSDT, TRTEDT) %>%
  rename(TRTA = TRT01A, TRTAN = TRT01AN) %>%
  mutate(TRTSDT = to_date(TRTSDT), TRTEDT = to_date(TRTEDT))

# Merge: SAS "merge AE(in=inAE) TEMP; by USUBJID; if inAE" keeps every AE row.
# That equals left_join ONLY if USUBJID is unique in TEMP. With repeated keys on both sides SAS
# pairs rows one-to-one, dplyr makes a Cartesian product. So I check uniqueness first.
stopifnot(!anyDuplicated(temp$USUBJID))
n_ae <- nrow(ae)
ae <- ae %>% left_join(temp, by = "USUBJID")
stopifnot(nrow(ae) == n_ae)   # a left join on a unique key must not change the row count

# Step 4: second data step.
# SAS length() ignores trailing blanks; I trim the right side. In R nchar(NA) is 2, so guard NA.
ae <- ae %>%
  mutate(
    .imp   = is.na(ASTDT) & !is.na(AESTDTC) & nchar(str_trim(AESTDTC, "right")) == 7,
    ASTDT  = if_else(.imp, parse_ymd10(paste0(AESTDTC, "-01")), ASTDT),
    ASTDTF = if_else(.imp, "D", "")   # SAS char missing is a blank, not NA. I use "".
  )
# Note: SAS sets ASTDTF='D' even if the imputed date turns out invalid (the input() here has no ??).
# My code does the same: .imp does not test the result.

# Relative days. SAS: "ASTDT>=TRTSDT>.z" is (ASTDT>=TRTSDT) AND (TRTSDT>.z).
# A SAS missing is smaller than any number, so missing ASTDT>=TRTSDT is FALSE (not NA).
# R would give NA, so every condition tests is.na() explicitly.
# No day 0: dates before TRTSDT get ASTDT-TRTSDT (negative), dates on or after get +1.
rel_day <- function(d, ref) {
  case_when(
    !is.na(ref) & !is.na(d) & d >= ref ~ as.numeric(d - ref) + 1,
    !is.na(ref) & !is.na(d) & d <  ref ~ as.numeric(d - ref),
    TRUE ~ NA_real_
  )
}
ae <- ae %>%
  mutate(
    ASTDY = rel_day(ASTDT, TRTSDT),
    AENDY = rel_day(AENDT, TRTSDT),
    # ANLSTDY is computed in SAS but is not in the final keep list, so I do not create it.
    # SAS: ELSE branch gives 'N' also when ASTDT or TRTSDT is missing. Same here: not NA.
    TRTEMFL = if_else(!is.na(TRTSDT) & !is.na(ASTDT) & ASTDT >= TRTSDT, "Y", "N"),
    # SAS index() is case-sensitive and returns a position; R str_detect(fixed()) is case-sensitive too.
    # SAS: aedecod not in (...) is TRUE for a missing aedecod. R: !(NA %in% x) is TRUE. Same.
    # SAS compares character values ignoring trailing blanks; R does not, so I trim both sides.
    aedecod_trim = coalesce(str_trim(AEDECOD), ""),
    .b = coalesce(str_trim(AEBODSYS), ""),
    CQ01NAM = if_else(
      str_detect(aedecod_trim, fixed("APPLICATION")) | str_detect(aedecod_trim, fixed("DERMATITIS")) |
      str_detect(aedecod_trim, fixed("ERYTHEMA"))    | str_detect(aedecod_trim, fixed("BLISTER"))    |
      (.b == "SKIN AND SUBCUTANEOUS TISSUE DISORDERS" & !(aedecod_trim %in% c("COLD SWEAT", "HYPERHIDROSIS", "ALOPECIA"))),
      "DERMATOLOGIC EVENTS", ""        # SAS char missing = blank
    )
  )

# Step 5: macro flagfrst, written as a function that returns a "Y"/"" vector aligned to ae.
# SAS: sort by usubjid &sortvars ASTDT within the where filter, then first.<invar> in a BY group
# of (usubjid, &sortvars). So the group is USUBJID + sortvars, and the first row after sorting by ASTDT wins.
# Ties on ASTDT: SAS PROC SORT keeps input order (EQUALS), and the input is in USUBJID, AESEQ order
# after the earlier sort and merge, so the lowest AESEQ wins. arrange() is stable, so the same here.
# [relies on ae still being sorted by AESEQ, so I re-sort before calling]
# Missing ASTDT would sort first in SAS and last in R, but TRTEMFL='Y' requires a non-missing ASTDT, so it cannot occur.
# The SAS merge back is by (usubjid, aeseq): assumes that pair is unique. I check it.
flag_first <- function(df, sortvars = character(0), invar = "", ser = FALSE, derm = FALSE) {
  d <- df %>% filter(TRTEMFL == "Y")
  if (invar != "") d <- d %>% filter(!is.na(.data[[invar]]), str_trim(.data[[invar]]) != "")
  if (ser)  d <- d %>% filter(AESER == "Y")
  if (derm) d <- d %>% filter(CQ01NAM == "DERMATOLOGIC EVENTS")
  first <- d %>%
    arrange(USUBJID, across(all_of(sortvars)), ASTDT) %>%
    group_by(across(all_of(c("USUBJID", sortvars)))) %>%
    slice_head(n = 1) %>%
    ungroup()
  if_else(paste(df$USUBJID, df$AESEQ) %in% paste(first$USUBJID, first$AESEQ), "Y", "")
}
stopifnot(!anyDuplicated(ae[c("USUBJID", "AESEQ")]))

ae <- ae %>% arrange(USUBJID, AESEQ)
ae <- ae %>%
  mutate(
    AOCCFL   = flag_first(.),
    AOCCSFL  = flag_first(., "AEBODSYS", "AEBODSYS"),
    AOCCPFL  = flag_first(., c("AEBODSYS", "AEDECOD"), "AEDECOD"),
    AOCC02FL = flag_first(., ser = TRUE),
    AOCC03FL = flag_first(., "AEBODSYS", "AEBODSYS", ser = TRUE),
    AOCC04FL = flag_first(., c("AEBODSYS", "AEDECOD"), "AEDECOD", ser = TRUE),
    AOCC01FL = flag_first(., derm = TRUE)
  )
# Note: flag_first(.) inside mutate sees the data frame as it is at that point, which already
# contains TRTEMFL, ASTDT and CQ01NAM, so it is the same input the SAS macro sees.

# Step 6: final selection and order (retain + keep list).
adae_r <- ae %>%
  select(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)

sas <- read_xpt(file.path(data_dir, "adam_adae.xpt"))
sas <- sas %>% mutate(across(c(TRTSDT, TRTEDT, ASTDT, AENDT), to_date)) %>% arrange(USUBJID, AESEQ)
r   <- adae_r %>% arrange(USUBJID, AESEQ)

# 1. Row counts and key uniqueness
cat("rows SAS:", nrow(sas), " rows R:", nrow(r), "\n")
stopifnot(nrow(sas) == nrow(r), !anyDuplicated(sas[c("USUBJID","AESEQ")]), !anyDuplicated(r[c("USUBJID","AESEQ")]))

# 2. Column names: report what is in one and not the other BEFORE comparing values
cat("only in SAS:", setdiff(names(sas), names(r)), "\n")
cat("only in R:  ", setdiff(names(r), names(sas)), "\n")
common <- intersect(names(sas), names(r))

# 3. Value by value. Tolerance: 0 for every column. All variables are text, dates stored as whole
# days, or whole-number day counts, so any difference is a real difference. A tolerance of 1e-8
# is only to absorb floating point noise in numeric columns, it cannot hide a one-day shift.
norm <- function(x) if (is.character(x)) coalesce(str_trim(x), "") else x
diffs <- lapply(common, function(v) {
  a <- norm(sas[[v]]); b <- norm(r[[v]])
  bad <- if (is.numeric(a) || inherits(a, "Date")) !((is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & abs(as.numeric(a) - as.numeric(b)) <= 1e-8)) else a != b
  tibble(variable = v, n_diff = sum(bad, na.rm = TRUE) + sum(is.na(bad)))
}) %>% bind_rows()
print(diffs %>% filter(n_diff > 0))   # empty = identical
# For any variable with differences: print the first 10 rows of USUBJID, AESEQ, SAS value, R value.
