"""Which AASD key means LEFT? Cross-validated backward decoder on the mixture envelope, then per attention segment
(between presses) d = r(recon, env_L) - r(recon, env_R); compare segments that follow key 179 vs key 184."""
import sys, numpy as np, scipy.io as sio
sys.path.insert(0, __file__.rsplit("/", 1)[0])
from verify_mapping import X, BP, env, lag
from scipy.signal import sosfiltfilt
def load(subj):
    d = sio.loadmat(f"{X}/Processed EEG/{subj}/{subj}.mat", squeeze_me=True, struct_as_record=False)["EEG_new"]
    st, presses = {}, {}
    for r in d.event:
        c, lat, e = int(float(r[0])), float(r[1]), int(float(r[4]))
        if c not in (179, 184):
            st.setdefault(e, c)
        else:
            presses.setdefault(e, []).append(((lat - (e - 1) * 7680 - 1) / 4.0, c))   # sample at 32 Hz within the epoch
    tr = []
    for ep in range(1, 51):
        x = sosfiltfilt(BP, d.data[:, :, ep - 1].T.astype(float), axis=0)[::4]
        x -= x.mean(1, keepdims=True); x = (x - x.mean(0)) / (x.std(0) + 1e-9)
        tr.append((x, st[ep] - 10, sorted(presses.get(ep, []))))
    return tr
for subj in ("S1", "S12", "S13"):
    tr = load(subj); res = {179: [], 184: []}
    idx = np.arange(len(tr))
    for f in np.array_split(idx, 5):
        trn = [i for i in idx if i not in f]
        Xs = np.vstack([lag(tr[i][0]) for i in trn]); Y = np.concatenate([env(tr[i][1])[:len(tr[i][0])].sum(1) for i in trn])
        n = min(len(Xs), len(Y)); w = np.linalg.solve(Xs[:n].T @ Xs[:n] + 1e2 * np.eye(Xs.shape[1]), Xs[:n].T @ Y[:n])
        for i in f:
            x, a, pr = tr[i]; y = lag(x) @ w; e = env(a)[:len(y)]
            bounds = [int(p) for p, _ in pr] + [len(e)]
            for (p, key), q in zip(pr, bounds[1:]):
                p = int(p) + 16                                      # skip 0.5 s after the press
                if q - p < 96: continue                              # segments >= 3 s
                rL = np.corrcoef(y[p:q], e[p:q, 0])[0, 1]; rR = np.corrcoef(y[p:q], e[p:q, 1])[0, 1]
                res[key].append(rL - rR)
    print(subj, "mean r_L - r_R after key 179: %+.4f (n=%d) | after key 184: %+.4f (n=%d)" % (
        np.mean(res[179]), len(res[179]), np.mean(res[184]), len(res[184])), flush=True)
