# derive_adae.py  (workflow: define-derivation-pseudocode)
# The Python the AI wrote from the define.xml text, exactly as written (the cold draft).
# Needs: Python 3, pandas, numpy. Run with: python -I derive_adae.py sdtm_ae.xpt adam_adsl.xpt out.csv
# Data are NOT included: download the unmodified CDISC pilot files sdtm_ae.xpt, adam_adsl.xpt and adam_adae.xpt from
# https://github.com/cdisc-org/sdtm-adam-pilot-project (updated-pilot-submission-package/900172/m5/). Credit: CDISC.
# Licence: MIT (see LICENSE.txt). Header added on 2026-10-24; the code below is unchanged.
"""ADAE derivations from define.xml text, cold draft. Usage: python -I derive_adae.py sdtm_ae.xpt adam_adsl.xpt out.csv"""
import sys
import numpy as np
import pandas as pd

ae = pd.read_sas(sys.argv[1], format="xport", encoding="latin1")
adsl = pd.read_sas(sys.argv[2], format="xport", encoding="latin1")

def to_days(s):
    """TRTSDT: SAS date -> days since 1960-01-01 as float (NaN if missing)."""
    if np.issubdtype(s.dtype, np.datetime64):
        return (s - pd.Timestamp("1960-01-01")).dt.days.astype(float)
    return s.astype(float)

adsl = adsl.assign(TRTSDT=to_days(adsl["TRTSDT"]))
d = ae.merge(adsl[["USUBJID", "TRTSDT"]], on="USUBJID", how="left")

EPOCH = pd.Timestamp("1960-01-01")

def parse_start(s):
    """Return (SAS date number, imputation flag). Day missing -> '01' and flag 'D'.
    Month and day missing -> no imputation, date stays missing. Time part ignored."""
    s = (s or "").strip()[:10]
    parts = s.split("-")
    if len(parts) == 3 and len(parts[2]) == 2:
        dt = pd.to_datetime(s, errors="coerce"); flag = ""
    elif len(parts) == 2:
        dt = pd.to_datetime(s + "-01", errors="coerce"); flag = "D"
    else:
        return np.nan, ""
    return ((dt - EPOCH).days if pd.notna(dt) else np.nan), flag

def parse_end(s):
    """Plain conversion; a partial end date is left missing (the text gives no imputation rule)."""
    s = (s or "").strip()[:10]
    if len(s) == 10:
        dt = pd.to_datetime(s, errors="coerce")
        return (dt - EPOCH).days if pd.notna(dt) else np.nan
    return np.nan

st = d["AESTDTC"].map(parse_start)
d["ASTDT"] = st.map(lambda t: t[0]); d["ASTDTF"] = st.map(lambda t: t[1])
d["AENDT"] = d["AEENDTC"].map(parse_end)

def rel_day(x, ref):
    # SAS: x>=ref>missing -> x-ref+1 ; ref>x>missing -> x-ref ; otherwise missing
    out = pd.Series(np.nan, index=x.index)
    ok = x.notna() & ref.notna()
    out[ok & (x >= ref)] = (x - ref + 1)[ok & (x >= ref)]
    out[ok & (x < ref)] = (x - ref)[ok & (x < ref)]
    return out
d["ASTDY"] = rel_day(d["ASTDT"], d["TRTSDT"])
d["AENDY"] = rel_day(d["AENDT"], d["TRTSDT"])
d["ADURN"] = d["AENDT"] - d["ASTDT"] + 1
d["ADURU"] = np.where(d["ADURN"].notna(), "DAY", "")

d["TRTEMFL"] = np.where(d["ASTDT"].notna() & d["TRTSDT"].notna() & (d["ASTDT"] >= d["TRTSDT"]), "Y", "N")

# CQ01NAM
dec = d["AEDECOD"].fillna("").str.upper()
hit_str = dec.apply(lambda x: any(k in x for k in ("APPLICATION", "DERMATITIS", "ERYTHEMA", "BLISTER")))
hit_soc = (d["AEBODSYS"].fillna("") == "SKIN AND SUBC UTANEOUS TISSUE DISORDERS") & ~dec.isin(["COLD SWEAT", "HYPERHIDROSIS", "ALOPECIA"])
d["CQ01NAM"] = np.where(hit_str | hit_soc, "DERMATOLOGIC EVENTS", "")

def first_flag(df, mask, by):
    """Flag first record per `by` after sorting by by + ASTDT + AESEQ, within rows where mask is True."""
    sub = df[mask].sort_values(by + ["ASTDT", "AESEQ"])
    first = sub.groupby(by, sort=False).head(1).index
    return np.where(df.index.isin(first), "Y", "")

te = d["TRTEMFL"] == "Y"
d["AOCCFL"] = first_flag(d, te, ["USUBJID"])
d["AOCCSFL"] = first_flag(d, te, ["USUBJID", "AEBODSYS"])
d["AOCCPFL"] = first_flag(d, te, ["USUBJID", "AEBODSYS", "AEDECOD"])
d["AOCC02FL"] = first_flag(d, te & (d["AESER"] == "Y"), ["USUBJID"])
# AOCC01FL: text says CQ01NAM='' but the label and comment say first dermatologic event, so I used CQ01NAM nonblank (flagged as ambiguity).
d["AOCC01FL"] = first_flag(d, te & (d["CQ01NAM"] != ""), ["USUBJID"])

cols = ["USUBJID", "AESEQ", "ASTDT", "ASTDTF", "ASTDY", "AENDT", "AENDY", "ADURN", "ADURU", "TRTSDT",
        "TRTEMFL", "AOCCFL", "AOCCSFL", "AOCCPFL", "AOCC02FL", "CQ01NAM", "AOCC01FL"]
d[cols].to_csv(sys.argv[3], index=False)
print("records:", len(d))
print("TRTEMFL=Y:", int((d.TRTEMFL == "Y").sum()))
for c in ["ASTDTF", "AOCCFL", "AOCCSFL", "AOCCPFL", "AOCC02FL", "AOCC01FL"]:
    print(c, "= flagged:", int((d[c] != "").sum()))
print("CQ01NAM nonblank:", int((d.CQ01NAM != "").sum()))
print("ASTDT missing:", int(d.ASTDT.isna().sum()), " AENDT missing:", int(d.AENDT.isna().sum()))
print("AEBODSYS values containing SKIN:", sorted(set(x for x in d.AEBODSYS.dropna() if "SKIN" in x.upper())))
