# ---------------------------------------------------------------------------
# run_bad.R  (workflow: adam-spec-row-to-r-code)
# Reproduces: The AI-written code for the spec rows, kept exactly as the model wrote it. It assumes data frames ae and adsl already exist, so it is sourced by harness_bad.R and is not meant to be run alone.
# Usage: (helper; run via harness_bad.R)
#   data_dir = folder containing the input files below (default: current folder).
# Input files: none (no data read)
#   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: none (helper).
# Packages: dplyr 1.2.1, lubridate 1.9.5. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Note: library-only helper
# 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.
# ---------------------------------------------------------------------------
library(dplyr)
library(lubridate)

adae <- ae %>%
  left_join(adsl %>% select(USUBJID, TRTSDT, TRTEDT), by = "USUBJID") %>%
  mutate(
    ASTDT   = ymd(AESTDTC),
    AENDT   = ymd(AEENDTC),
    TRTEMFL = if_else(ASTDT >= TRTSDT & ASTDT <= TRTEDT + 30, "Y", "N"),
    ASTDY   = as.numeric(ASTDT - TRTSDT) + 1,
    AENDY   = as.numeric(AENDT - TRTSDT) + 1,
    ADURN   = as.numeric(AENDT - ASTDT) + 1,
    ADURU   = if_else(!is.na(ADURN), "DAYS", NA_character_)
  ) %>%
  arrange(USUBJID, ASTDT) %>%
  group_by(USUBJID) %>%
  mutate(AOCCFL = if_else(row_number() == 1 & TRTEMFL == "Y", "Y", NA_character_)) %>%
  ungroup()
