"""Secondary analyses listed in the plan but not in code/meta.py, plus one post hoc check.

(a) planned: Caceda et al. 2020 restricted to the non-suicidal depressed group;
(b) planned, descriptive: melancholic / severe versus other depressed subgroups where a study
    reports them (Tysk 1984; Munzel et al. 1988);
(c) post hoc: Mundt et al. 1998 without its 10-s row (possible typesetting error).
Writes results/R2.json. Usage: python code/sensitivity.py
"""
import csv
import json
import os
import shutil
import sys
import tempfile

sys.path.insert(0, "code")
import meta  # noqa: E402


def run_with(filter_fn):
    tmp = tempfile.mkdtemp()
    os.makedirs(os.path.join(tmp, "data"))
    with open("data/extraction.csv", newline="") as fh:
        rows = list(csv.DictReader(fh))
    kept = [r for r in rows if filter_fn(r)]
    with open(os.path.join(tmp, "data/extraction.csv"), "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(kept)
    shutil.copy("data/secondary.csv", os.path.join(tmp, "data/secondary.csv"))
    cwd = os.getcwd()
    os.chdir(tmp)
    try:
        per = meta.primary_effects("data/extraction.csv")
        res = meta.meta_regression(meta.by_zone(per) + meta.secondary_effects("data/secondary.csv"))
    finally:
        os.chdir(cwd)
    return res


def subgroup_g(study, contrast_substring, interval):
    with open("data/extraction.csv", newline="") as fh:
        for r in csv.DictReader(fh):
            if r["study"] == study and contrast_substring in r["group_contrast"] and float(r["interval_s"]) == interval:
                g, v = meta.hedges(int(r["n_dep"]), float(r["mean_dep"]), float(r["sd_dep"]), int(r["n_ctl"]),
                                   float(r["mean_ctl"]), float(r["sd_ctl"]), r["higher_value_means"])
                return round(g, 3)
    return None


def main():
    out = {}
    a = run_with(lambda r: not (r["study"] == "Caceda et al. 2020" and "non-suicidal" not in r["group_contrast"]))
    out["a_caceda_nonsuicidal_only"] = {k: a[k] for k in ("moment", "beyond", "difference_beyond_minus_moment")}
    out["b_subgroups_descriptive"] = {
        "Tysk 1984": {f"{iv} s": {grp: subgroup_g("Tysk 1984", grp, iv) for grp in
                                  ("major depression with melancholia", "bipolar depression", "major depression without melancholia", "dysthymic disorder")}
                      for iv in (20.0, 30.0)},
        "Munzel et al. 1988": {f"{iv} s": {grp: subgroup_g("Munzel et al. 1988", grp, iv) for grp in
                                           ("high subjective depression", "low subjective depression", "neurotic depression")}
                               for iv in (1.0, 5.0, 10.0)},
    }
    c = run_with(lambda r: not (r["study"] == "Mundt et al. 1998" and float(r["interval_s"]) == 10.0))
    out["c_post_hoc_mundt_without_10s"] = {k: c[k] for k in ("moment", "beyond", "difference_beyond_minus_moment")}
    # dot-free summaries for citing in the paper
    sub = out["b_subgroups_descriptive"]
    with open("results/R1.json") as fh:
        r1 = json.load(fh)
    loo = r1["leave_one_study_out_difference"]
    kit = [e for e in r1["effects_by_study_zone"] if e["study"].startswith("Kitamura")][0]
    out["summary"] = {
        "loo_min": min(loo.values()), "loo_max": max(loo.values()),
        "munzel_1s_high": sub["Munzel et al. 1988"]["1.0 s"]["high subjective depression"],
        "munzel_1s_low": sub["Munzel et al. 1988"]["1.0 s"]["low subjective depression"],
        "munzel_1s_neurotic": sub["Munzel et al. 1988"]["1.0 s"]["neurotic depression"],
        "tysk_30s_melancholic": sub["Tysk 1984"]["30.0 s"]["major depression with melancholia"],
        "tysk_30s_dysthymic": sub["Tysk 1984"]["30.0 s"]["dysthymic disorder"],
        "kitamura_g": round(kit["g"], 3),
        "kitamura_target_s": 30, "thones_long_range_min": 10,
        "munzel_short_target_s": 1, "tysk_target_s": 30,
    }
    with open("results/R2.json", "w") as fh:
        json.dump(out, fh, indent=2, sort_keys=True)
        fh.write("\n")
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
