"""Multi-scale evidence from the reconstruction decoder (needs run_experiment.py --save-recon, GLIMPSE_THR as trained).

For every held-out trial: the synthetic-switch schedule of score.py is replayed and the stimulus columns are swapped at
the switch times (as for the direct classifier), then per-target Pearson correlations between the causal
reconstruction and both streams are taken over the LAST L seconds available at each 0.25-s decision (same timing as
the classifier: decision for hop a uses reconstruction samples < a + 8, i.e. EEG up to a + 24 samples = 0.75 s
lookahead). Targets are combined with LDA weights fitted on the other four datasets.
Writes a classifier-format pseudo experiment folds/<EXP>_ms<L>/ + results json, usable as --clf in fuse_general.py.
usage: GLIMPSE_THR=norm python multiscale_decoder.py EXP 3 5 [...]"""
import json
import os
import pickle
import sys

import numpy as np

import decoders
import score as S
from common_exp import EXP, FS, fold_file, load_trial, rows_of, save_pickle
from common import DS_KEYS, SEED
from e1_switch import draw_switch_times

HOP = 8


def trial_evidence(rec, Sx, att, T128, t0, times, Ls):
    st128, cur, prev = np.zeros(T128, bool), False, 0
    for tt in times:
        s0 = min(T128 - 1, int(round(tt * 128)))
        st128[prev:s0] = cur
        cur, prev = not cur, s0
    st128[prev:] = cur
    T = len(rec)
    st = st128[np.minimum(T128 - 1, np.round((np.arange(T) / FS + t0) * 128).astype(int))]
    Ssw = np.where(st[:, None, None], Sx[:, ::-1], Sx)[:T]
    starts = np.arange(0, T, HOP)
    truth = (att[:T] ^ st)[np.maximum(starts - HOP, 0)]
    cs = lambda x: np.concatenate([np.zeros((1,) + x.shape[1:]), np.cumsum(x, 0)], 0)
    y = rec.astype(np.float64)
    out = {}
    for L in Ls:
        W = int(L * FS)
        e = np.minimum(starts + HOP, T)                       # exclusive end of the correlation window
        b = np.maximum(e - W, 0)
        n = (e - b)[:, None]

        def corr(a_, b_):
            sa, sb, sab = cs(a_), cs(b_), cs(a_ * b_)
            saa, sbb = cs(a_ * a_), cs(b_ * b_)
            win = lambda c: c[e] - c[b]
            cov = win(sab) - win(sa) * win(sb) / n
            va, vb = np.maximum(win(saa) - win(sa) ** 2 / n, 1e-12), np.maximum(win(sbb) - win(sb) ** 2 / n, 1e-12)
            return cov / np.sqrt(va * vb)
        out[L] = (corr(y, Ssw[:, 0].astype(np.float64)) - corr(y, Ssw[:, 1].astype(np.float64))).astype(np.float32)   # (n, F)
    return out, truth.astype(np.int8), (starts / FS + t0).astype(np.float32)


if __name__ == "__main__":
    exp, Ls = sys.argv[1], [float(x) for x in sys.argv[2:]]
    rj = json.load(open(os.path.join(EXP, "results", f"{exp}.json")))
    decoders.D["targets"] = rj["targets"]
    data = {}
    for ds in DS_KEYS:
        rec = pickle.load(open(fold_file(exp, ds), "rb"))["recon"]
        rng = np.random.default_rng(SEED + DS_KEYS.index(ds))
        data[ds] = {}
        for _, r in rows_of(ds).iterrows():
            T128 = int(r["n"])
            times = draw_switch_times(rng, T128 / 128)
            rng.integers(0, 2)
            tr = load_trial(rj["prep"], r["key"])
            data[ds][r["key"]] = trial_evidence(rec[r["key"]], decoders._targets(tr), tr["att"].astype(int), T128, tr["t0"], times, Ls)
    for L in Ls:
        name = f"{exp}_ms{L:g}"
        for ds in DS_KEYS:
            X = np.concatenate([d[0][L] * np.where(d[1] == 0, 1.0, -1.0)[:, None] for o in DS_KEYS if o != ds for d in data[o].values()])
            w = np.linalg.solve(np.cov(X.T), X.mean(0))
            w /= np.abs(w).sum()
            ev = {}
            for k, (D, truth, t_end) in data[ds].items():
                d = D[L] @ w
                n10 = len(d) // 40
                ev[k] = dict(r0=d / 2, r1=-d / 2, att=truth, t_end=t_end, r0_10=d[:n10 * 40].reshape(n10, 40).mean(1) / 2,
                             r1_10=-d[:n10 * 40].reshape(n10, 40).mean(1) / 2, att10=(truth[:n10 * 40].reshape(n10, 40).mean(1) > 0.5).astype(np.int8),
                             pre_switched=True)
            save_pickle(dict(evidence={"causal": ev}, info=dict(decoder="multiscale", prep=rj["prep"], held_out=ds, lookahead_s=0.75, window_s=L,
                                                                 weights=[float(x) for x in w])), fold_file(name, ds))
        res = S.score_experiment(name, "causal", 0.75)
        m = res["mean"]
        json.dump(dict(experiment=name, decoder="multiscale", prep=rj["prep"], source=exp, corr_window_s=L, causal=res),
                  open(os.path.join(EXP, "results", f"{name}.json"), "w"), indent=1, default=float)
        print(f"{name}: H {m['H']:.4f} Acc {m['Acc']:.2f} SDT {m['SDT']:.2f} | " + " ".join(f"{d} {v['H']:.3f}" for d, v in res["per_dataset"].items()), flush=True)
