# ---------------------------------------------------------------------------
# run_bad_filenames.R  (workflow: sas-to-r-translation)
# Reproduces: The weaker answer's code with the file names corrected. It still stops with a dplyr error (column TRTA is not found), which is the point: the code was never run against the real files.
# Usage: Rscript run_bad_filenames.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/run_bad_filenames_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
library(dplyr)
library(haven)

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

adae <- ae %>%
  left_join(adsl, by = "USUBJID") %>%
  mutate(
    AESTDT = as.Date(AESTDTC),
    TRTEMFL = ifelse(AESTDT >= TRTSDT, "Y", ""),
    AEBODSYS = toupper(AEBODSYS)
  ) %>%
  filter(SAFFL == "Y")

ae_table <- adae %>%
  filter(TRTEMFL == "Y") %>%
  group_by(TRTA, AEBODSYS, AEDECOD) %>%
  summarise(n = n_distinct(USUBJID), .groups = "drop") %>%
  left_join(adsl %>% count(TRT01A, name = "N"), by = c("TRTA" = "TRT01A")) %>%
  mutate(pct = round(100 * n / N, 1))

# ---- appended by R specialist to show what happens (not AI code) ----
cat("\nclass(adae$AESTDT):", class(adae$AESTDT), "\n")
print(head(ae_table))
