"""Verify the AASD trial -> audio mapping (hypothesis: mixed_{code-10:03d}.wav, code = trial-start trigger 11..70)
with a cross-validated linear backward decoder on the MIXTURE envelope (independent of the attention labels):
the correct mapping must give a clearly higher reconstruction correlation than shifted / shuffled mappings."""
import glob, os, sys
import numpy as np, scipy.io as sio
from scipy.io import wavfile
from scipy.signal import butter, sosfiltfilt
sys.path.insert(0, "/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/experiments/envelope_reverse")
from reverse import candidates
X = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/extract"
BP = butter(2, [1, 9], "bandpass", fs=128, output="sos")
envc = {}
def env(n):
    if n not in envc:
        fs, a = wavfile.read(f"{X}/Stimuli Audio/mixed_{n:03d}.wav")
        e = np.stack([candidates(a[:, c].astype(float), fs)["gt_pow06"] for c in range(2)], 1)
        e = sosfiltfilt(BP, e, axis=0)[::4]
        envc[n] = (e - e.mean(0)) / e.std(0)
    return envc[n]
def trials(subj):
    d = sio.loadmat(f"{X}/Processed EEG/{subj}/{subj}.mat", squeeze_me=True, struct_as_record=False)["EEG_new"]
    st = {}
    for r in d.event:
        c, e = int(float(r[0])), int(float(r[4]))
        if c not in (179, 184) and e not in st: st[e] = c
    out = []
    for ep in range(1, 51):                                   # first 50 trials (block 7 = passive control)
        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)
        out.append((x, st[ep]))
    return out
def lag(x, L=8):
    return np.hstack([np.vstack([x[l:], np.zeros((l, x.shape[1]))]) for l in range(L)])   # EEG after stimulus
def cv_r(tr, mapf):
    rs = []
    idx = np.arange(len(tr)); folds = np.array_split(idx, 5)
    for f in folds:
        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(mapf(tr[i][1]))[:len(tr[i][0])].sum(1) for i in trn])
        n = min(len(Xs), len(Y)); Xs, Y = Xs[:n], Y[:n]
        w = np.linalg.solve(Xs.T @ Xs + 1e2 * np.eye(Xs.shape[1]), Xs.T @ Y)
        for i in f:
            y = lag(tr[i][0]) @ w; e = env(mapf(tr[i][1]))[:len(y)].sum(1); m = min(len(y), len(e))
            rs.append(np.corrcoef(y[:m], e[:m])[0, 1])
    return float(np.mean(rs))
rng = np.random.default_rng(0); perm = rng.permutation(60) + 1
for subj in ("S1", "S12", "S13"):
    tr = trials(subj)
    print(subj, "r(code-10) %.3f | r(code-9) %.3f | r(code-11) %.3f | r(shuffled) %.3f" % (
        cv_r(tr, lambda c: c - 10), cv_r(tr, lambda c: (c - 10) % 60 + 1), cv_r(tr, lambda c: (c - 12) % 60 + 1),
        cv_r(tr, lambda c: perm[c - 11])), flush=True)
