# Verifier sensitivity checks (not part of the bundle): same data and metrics as code/rhythm.py.
import json, sys
import numpy as np, pandas as pd, statsmodels.api as sm
from scipy import stats
sys.path.insert(0, "code")
import rhythm as R
m = R.build("data/nhanes-pax"); m["age2"] = m["RIDAGEYR"] ** 2
base = ["RIDAGEYR", "age2", "male", "cycleH", "exam_nov_apr"]
out = {"n": int(len(m))}
def ci(r):
    se = abs(r["beta_std"] / r["t"]) if r["t"] else float("nan")
    return dict(r, ci95=[round(r["beta_std"] - 1.96 * se, 4), round(r["beta_std"] + 1.96 * se, 4)])
out["IV_registered"] = ci(R.rank_reg(m, "IV", "phq", base, 1))
out["IV_adj_activity"] = ci(R.rank_reg(m, "IV", "phq", base + ["mean_activity"], 1))
out["AR1_adj_RA_IS_activity"] = ci(R.rank_reg(m, "AR1", "phq", base + ["mean_activity", "RA", "IS"], 1))
out["IS_adj_RA_activity"] = ci(R.rank_reg(m, "IS", "phq", base + ["mean_activity", "RA"], -1))
# conventional interaction: ranked outcome, ranked PHQ, centred age, product of centred PHQ rank and centred age, no ranking of the product
def inter(y):
    d = m.dropna(subset=[y]).copy()
    pr = stats.rankdata(d["phq"]); pr = (pr - pr.mean()) / pr.std()
    ac = (d["RIDAGEYR"] - d["RIDAGEYR"].mean()) / 10
    X = pd.DataFrame({"phq_rank_z": pr, "age_c10": ac.values, "age2": d["age2"].values, "male": d["male"].values,
                      "cycleH": d["cycleH"].values, "exam": d["exam_nov_apr"].values})
    X["phq_x_age10"] = X["phq_rank_z"] * X["age_c10"]
    yr = stats.rankdata(d[y]); yr = (yr - yr.mean()) / yr.std()
    f = sm.OLS(yr, sm.add_constant(X)).fit(cov_type="HC3")
    return {"phq_main_per_sd": round(float(f.params["phq_rank_z"]), 4), "interaction_per_sd_per_decade": round(float(f.params["phq_x_age10"]), 4),
            "interaction_p_two_sided": float(f.pvalues["phq_x_age10"])}
out["IV_interaction_conventional"] = inter("IV")
out["IS_interaction_conventional"] = inter("IS")
# age-stratified PHQ slopes for IV and IS
for lo, hi in [(20, 39), (40, 59), (60, 200)]:
    s = m[(m["RIDAGEYR"] >= lo) & (m["RIDAGEYR"] <= hi)]
    out[f"IV_age_{lo}_{hi}"] = ci(R.rank_reg(s, "IV", "phq", base, 1))
    out[f"IS_age_{lo}_{hi}"] = ci(R.rank_reg(s, "IS", "phq", base, -1))
json.dump(out, open("sens_out.json", "w"), indent=1)
print(json.dumps(out, indent=1))
