"""#2: same AASD evidence, scored with REAL key-press switches vs SYNTHETIC switches (corpus procedure:
generateSyntheticSwitches schedule, evidence sign set relative to the true per-window attention).
usage: python aasd_synthetic.py -> results/research/aasd_real_vs_synthetic.json"""
import json, os, pickle
import numpy as np
import eval_external as E  # sets the import paths (common_exp)
from e1_switch import draw_switch_times, expand, integ_hmm
from scorer import aggregate, fast_score_subject
from common import FS as FS128, SEED
import eval_external as E

def score_syn(ev, mu, sd, p, rng, lookahead=0.75):
    per = {}
    for k in sorted(ev):
        e = ev[k]; T = e["n128"]
        times = draw_switch_times(rng, T / FS128)
        st = np.zeros(T, bool); cur, prev = bool(rng.integers(0, 2)), 0
        for tt in times:
            s0 = min(T - 1, int(round(tt * FS128))); st[prev:s0] = cur; cur, prev = not cur, s0
        st[prev:] = cur
        c = np.r_[0, np.cumsum(st)]
        a = np.clip(np.round((e["t_end"] - 1.0) * FS128).astype(int), 0, T); b = np.clip(np.round(e["t_end"] * FS128).astype(int), 0, T)
        syn_w = (c[b] - c[a]) > (b - a) / 2                       # window label 1 = synthetic attention on column 1
        s_true = np.where(e["att"] == 0, 1.0, -1.0); s_syn = np.where(syn_w, -1.0, 1.0)
        d = (e["r0"] - e["r1"]).astype(float) * s_true * s_syn
        dec = integ_hmm(d, dict(p_stay=p, mu=mu, sd=sd))
        labs = expand(dec, e["t_end"].astype(float), lookahead, T, int(rng.integers(0, 2)))
        per.setdefault(e["subject"], []).append((labs, st.astype(float)))
    res = []
    for s, lst in per.items():
        pred = np.concatenate([x for x, _ in lst]); gt = np.concatenate([y for _, y in lst])
        trial = np.concatenate([np.full(len(x), i) for i, (x, _) in enumerate(lst)])
        res.append(fast_score_subject(pred, gt, trial, fs=FS128))
    g = aggregate(res); return dict(Acc=g["Acc"], SDT=g["SDT"], L=g["L"], H=g["H"], nSwitches=g["nSwitches"])

if __name__ == "__main__":
    mu, sd = E.emissions(); out = {}
    for s in (0, 1):
        ev = pickle.load(open(f"results/research/aasd_c1_evidence_s{s}.pkl", "rb"))
        for p in (0.998, 0.95):
            real = E.score(ev, mu, sd, p); syn = score_syn(ev, mu, sd, p, np.random.default_rng(SEED))
            out[f"s{s}_p{p}"] = dict(real=real, synthetic=syn)
            print(f"seed {s} p_stay {p}: REAL Acc {real['Acc']:.1f} SDT {real['SDT']:.1f} H {real['H']:.3f} ({real['nSwitches']} sw) | "
                  f"SYNTHETIC Acc {syn['Acc']:.1f} SDT {syn['SDT']:.1f} H {syn['H']:.3f} ({syn['nSwitches']} sw)", flush=True)
    json.dump(out, open("results/research/aasd_real_vs_synthetic.json", "w"), indent=1, default=float)
