"""Hyper-parameter search of the causal Euclidean alignment WITHOUT carry across trials (test rule 6.3), with the linear
backward decoder (wf) as a fast proxy: start value (identity / population prior), its weight n0 (s of data), tau, shrinkage.
Per prep: build the cache (prepare_data.py), run the LODO experiment (run_experiment.py --decoder wf), collect H.
Reference rows: mat (no EA), mat_rea (identity, n0 = tau = 60), mat_reap (prior, n0 = tau = 60), mat_reac (carry, not allowed).
usage: python tune_ea.py  -> results/research/tune_ea.csv; the winners still have to be confirmed with the DNNs."""
import json
import os
import subprocess
import sys

import pandas as pd

from common_exp import CFG, EXP

PREPS = ["mat", "mat_rea", "mat_reap", "mat_reac"] + [p for p in CFG["preps"] if p.startswith(("eaI_", "eaP_"))]

if __name__ == "__main__":
    rows = []
    for p in PREPS:
        rj = os.path.join(EXP, "results", f"wf__{p}.json")
        if not os.path.exists(rj):
            subprocess.run([sys.executable, "prepare_data.py", p], cwd=EXP, check=True, stdout=subprocess.DEVNULL)
            subprocess.run([sys.executable, "run_experiment.py", "--decoder", "wf", "--prep", p], cwd=EXP, check=True, stdout=subprocess.DEVNULL)
        r = json.load(open(rj))["causal"]
        P = CFG["preps"][p]
        rows.append(dict(prep=p, start="carry" if P.get("ea_carry") else "prior" if P.get("ea_prior") else "identity" if P.get("ea") else "no EA",
                         n0=P.get("ea_n0", P.get("ea_tau", 60.0) if P.get("ea") else None), tau=P.get("ea_tau", 60.0 if P.get("ea") else None),
                         shrink=P.get("ea_shrink", 0.1 if P.get("ea") else None), H=r["mean"]["H"], Acc=r["mean"]["Acc"], SDT=r["mean"]["SDT"],
                         snr1=r["mean"]["snr1"], **{d: v["H"] for d, v in r["per_dataset"].items()}))
        pd.DataFrame(rows).to_csv(os.path.join(EXP, "results", "research", "tune_ea.csv"), index=False)
        print(rows[-1], flush=True)
    pd.set_option("display.width", 220)
    print("\n", pd.DataFrame(rows).sort_values("H", ascending=False).round(4).to_string(index=False))
