# ---------------------------------------------------------------------------
# harness_bad.R  (workflow: adam-spec-row-to-r-code)
# Reproduces: Reads sdtm_ae.xpt and adam_adsl.xpt, runs run_bad.R, and compares the result with the delivered ADAE (adam_adae.xpt) variable by variable: 14 non-key variables, TRTEMFL mismatches, ASTDY and AENDY offsets.
# Usage: Rscript harness_bad.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_bad_output.txt in this workflow's folder.
# Packages: 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.
# Note: Keep run_bad.R in the same folder as harness_bad.R.
# 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
# Harness only (not part of the AI output): the AI's code assumes data frames `ae` and `adsl` already exist.
# Note: lubridate is installed in tools/rlib. Inputs are read unmodified.
suppressMessages(library(haven))
src <- paste0(sub("/+$", "", data_dir), "/")
ae   <- read_xpt(file.path(src, "sdtm_ae.xpt"))
adsl <- read_xpt(file.path(src, "adam_adsl.xpt"))
cat("harness: class(adsl$TRTSDT) =", class(adsl$TRTSDT), "\n")
source(file.path(script_dir, "run_bad.R"), echo = FALSE)

# ---- comparison with the SAS-produced ADAE (R specialist code, not AI code) ----
suppressMessages(library(stringr))
ref <- read_xpt(file.path(src, "adam_adae.xpt"))
cat("rows: R =", nrow(adae), " xpt =", nrow(ref), "\n")
m <- merge(as.data.frame(ref), as.data.frame(adae), by = c("USUBJID", "AESEQ"), suffixes = c(".ref", ".r"))
cat("merged rows:", nrow(m), "\n")
vars <- c("AESEQ","TRTEMFL","ASTDT","ASTDTF","AENDT","ASTDY","AENDY","ADURN","ADURU","AOCCFL","AOCCSFL","AOCCPFL","AOCC02FL","CQ01NAM","AOCC01FL")
tot <- 0; ok <- 0
for (v in vars) {
  if (v %in% c("AESEQ")) { cat(v, "key\n"); next }
  if (!(paste0(v, ".r") %in% names(m))) { cat(sprintf("%-9s not produced\n", v)); tot <- tot + nrow(m); next }
  a <- m[[paste0(v, ".ref")]]; b <- m[[paste0(v, ".r")]]
  if (is.character(a) || is.character(b)) { a <- str_trim(coalesce(as.character(a), "")); b <- str_trim(coalesce(as.character(b), "")) }
  same <- (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)
  same[is.na(same)] <- FALSE
  tot <- tot + length(same); ok <- ok + sum(same)
  cat(sprintf("%-9s %d/%d\n", v, sum(same), length(same)))
}
cat(sprintf("TOTAL (14 non-key variables) %d/%d = %.2f%%\n", ok, tot, 100 * ok / tot))

# ---- breakdown of TRTEMFL mismatches ----
mm <- m[!(str_trim(m$TRTEMFL.ref) == str_trim(coalesce(m$TRTEMFL.r, "<NA>"))), ]
cat("TRTEMFL mismatches:", nrow(mm), "\n")
print(table(ref = mm$TRTEMFL.ref, R = ifelse(is.na(mm$TRTEMFL.r), "NA", mm$TRTEMFL.r)))
cat("by AESTDTC length of mismatches:\n"); print(table(nchar(mm$AESTDTC)))
cat("ASTDT NA in R by AESTDTC length:\n"); print(table(nchar(adae$AESTDTC)[is.na(adae$ASTDT)]))
cat("ADURU values in R:\n"); print(table(adae$ADURU, useNA = "ifany"))
cat("TRTEMFL counts R:\n"); print(table(adae$TRTEMFL, useNA = "ifany"))
cat("AOCCFL Y count R:", sum(adae$AOCCFL == "Y", na.rm = TRUE), " xpt:", sum(ref$AOCCFL == "Y"), "\n")

# ---- month-only start dates: what did ymd() return vs the SAS ASTDT ----
mo <- m[nchar(m$AESTDTC) == 7, c("USUBJID","AESEQ","AESTDTC","ASTDT.ref","ASTDT.r")]
print(mo)

# ---- ASTDY / AENDY breakdown ----
dd <- m$ASTDY.r - m$ASTDY.ref
cat("ASTDY mismatches:", sum(!(is.na(dd) & is.na(m$ASTDY.ref) & is.na(m$ASTDY.r)) & !(!is.na(dd) & dd == 0), na.rm = FALSE), "\n")
cat("ASTDY: R minus xpt == 1:", sum(dd == 1, na.rm = TRUE), " R NA & xpt not NA:", sum(is.na(m$ASTDY.r) & !is.na(m$ASTDY.ref)), " other nonzero:", sum(dd != 0 & dd != 1, na.rm = TRUE), "\n")
de <- m$AENDY.r - m$AENDY.ref
cat("AENDY: R minus xpt == 1:", sum(de == 1, na.rm = TRUE), " R NA & xpt not NA:", sum(is.na(m$AENDY.r) & !is.na(m$AENDY.ref)), " other nonzero:", sum(de != 0 & de != 1, na.rm = TRUE), "\n")
