# ---------------------------------------------------------------------------
# check_bad_asdate.R  (workflow: sas-to-r-translation)
# Reproduces: Shows what as.Date(AESTDTC) from the weaker answer does on the real data (errors or NA on year-only and month-only dates).
# Usage: Rscript check_bad_asdate.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: sdtm_ae.xpt; adam_adsl.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/check_bad_asdate_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5. 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
# Extra check by R specialist: what does as.Date(AESTDTC) (line in the bad answer) do on the real data?
suppressMessages(library(haven)); suppressMessages(library(dplyr))
ae <- read_xpt(file.path(data_dir, "sdtm_ae.xpt")); adsl <- read_xpt(file.path(data_dir, "adam_adsl.xpt"))
d <- tryCatch(as.Date(ae$AESTDTC), error = function(e) {cat("ERROR:", conditionMessage(e), "\n"); NULL})
if (!is.null(d)) {
  cat("as.Date(AESTDTC): NA count =", sum(is.na(d)), "of", length(d), "\n")
  cat("  NA among nchar==7:", sum(is.na(d) & nchar(ae$AESTDTC) == 7), " of ", sum(nchar(ae$AESTDTC) == 7), "\n")
  cat("  NA among nchar==4:", sum(is.na(d) & nchar(ae$AESTDTC) == 4), " of ", sum(nchar(ae$AESTDTC) == 4), "\n")
  x <- ae %>% left_join(adsl %>% select(USUBJID, TRTSDT), by = "USUBJID") %>% mutate(AESTDT = d, TRTEMFL = ifelse(AESTDT >= TRTSDT, "Y", ""))
  cat("TRTEMFL as the bad answer defines it:\n"); print(table(x$TRTEMFL, useNA = "ifany"))
  cat("month-only starts with TRTEMFL NA:", sum(is.na(x$TRTEMFL) & nchar(x$AESTDTC) == 7), "\n")
}
