# Standalone Colab cell: everyone aged >=40 in NHANES 2005-2008 (DEMO, DIQ, GHB, OPXRET) -> nhanes_all40.csv
import pandas as pd, numpy as np, io, urllib.request
def get(name, L, yr):
    for u in [f"https://wwwn.cdc.gov/Nchs/Data/Nhanes/Public/{yr}/DataFiles/{name}_{L}.xpt",
              f"https://wwwn.cdc.gov/Nchs/Nhanes/{yr}-{yr+1}/{name}_{L}.XPT"]:
        try:
            raw = urllib.request.urlopen(u, timeout=120).read()
            if raw[:6] == b"HEADER": return pd.read_sas(io.BytesIO(raw), format="xport")
        except Exception as e: print("  tried", u, "->", e)
    raise RuntimeError(f"Could not download {name}_{L}")
def c(df, *names):
    for n in names:
        if n in df.columns: return df[n]
    return pd.Series(np.nan, index=df.index)
out = []
for L, yr in [("D", 2005), ("E", 2007)]:
    demo, diq, ghb, opx = get("DEMO", L, yr), get("DIQ", L, yr), get("GHB", L, yr), get("OPXRET", L, yr)
    m = demo.merge(diq, on="SEQN", how="left").merge(ghb, on="SEQN", how="left")
    d = pd.DataFrame({"SEQN": m.SEQN, "cycle": L, "age": m.RIDAGEYR, "female": (m.RIAGENDR == 2).astype(float),
                      "wt": m.WTMEC2YR / 2, "strata": m.SDMVSTRA, "psu": m.SDMVPSU,
                      "dm_dx": (m.DIQ010 == 1).astype(float), "hba1c": c(m, "LBXGH")})
    agedx = c(m, "DID040", "DID040Q"); dur = d.age - agedx
    dur[agedx == 666] = 0; dur[agedx.isin([777, 999])] = np.nan; dur[dur < 0] = np.nan
    d["duration"] = dur
    ins = c(m, "DIQ050"); d["insulin"] = (ins == 1).astype(float).where(ins.isin([1, 2]))
    e = pd.DataFrame({"SEQN": opx.SEQN, "rl4_r": c(opx, "OPDDRL4"), "rl4_l": c(opx, "OPDSRL4"),
                      "ret_worse": c(opx, "OPDURET"), "grbl_r": c(opx, "OPXDGRBL"), "grbl_l": c(opx, "OPXSGRBL"),
                      "me_r": c(opx, "OPDDME"), "me_l": c(opx, "OPDSME")})
    out.append(d.merge(e, on="SEQN", how="left"))
x = pd.concat(out, ignore_index=True); x = x[x.age >= 40]
x.to_csv("nhanes_all40.csv", index=False)
try:
    from google.colab import files; files.download("nhanes_all40.csv")
except ImportError:
    print("Saved nhanes_all40.csv")
