"""Fuse the evidence of the reconstruction decoder (per-target correlations) with the direct classifier's logit.

Both run causally on the same 0.25-s grid; decoder window j is paired with classifier hop j + DEC_OFFSET (default 3: both
then use exactly the same EEG, the full 1-s budget; 4 = the older, 0.25 s more conservative pairing). The classifier's evidence is already synthetic-switched (direct_classifier.py); the decoder's is
flipped here with the SAME schedule (score.py's generator replayed). For held-out dataset D the fusion weights are
LDA weights fitted on the other four datasets' out-of-fold evidence (no test data); scoring = score.py unchanged.
  dec_equal : decoder targets, equal weights (sanity: reproduces the decoder experiment)
  dec_lda   : decoder targets, LDA weights
  clf       : classifier logit only (sanity: reproduces the classifier experiment)
  fused     : decoder targets + classifier logit, LDA weights
usage: python fuse_evidence.py DEC_EXP CLF_EXP [DEC_EXP CLF_EXP ...] -> results/research/fuse_evidence.csv"""
import json
import os
import sys

import numpy as np
import pandas as pd
from joblib import Parallel, delayed

import score as S
from common_exp import CFG, EXP, rows_of
from common import DS_KEYS, SEED
from e1_switch import draw_switch_times

LA = CFG["dnn"]["causal_future_s"] + CFG["dnn"]["infer_hop_s"]
OFF = int(os.environ.get("DEC_OFFSET", 3))          # 3 since 2026-10-04 (was 4), see features()


def features(dec, clf):
    """Per trial: X (n, F + 1) = switched decoder per-target evidence + classifier logit, att (n,), t_end (n,)."""
    evd, _ = S.load_folds(dec, "causal")
    evc, _ = S.load_folds(clf, "causal")
    out = {}
    for ds in DS_KEYS:
        rng = np.random.default_rng(SEED + DS_KEYS.index(ds))
        out[ds] = {}
        for _, r in rows_of(ds).iterrows():
            T = int(r["n"])
            times = draw_switch_times(rng, T / 128)
            rng.integers(0, 2)
            st, cur, prev = np.zeros(T, bool), False, 0
            for tt in times:
                s0 = min(T - 1, int(round(tt * 128)))
                st[prev:s0] = cur
                cur, prev = not cur, s0
            st[prev:] = cur
            ed, ec = evd[ds][r["key"]], evc[ds][r["key"]]
            te = ed["t_end"].astype(float)
            c = np.r_[0, np.cumsum(st)]
            a = np.clip(np.round((te - 1.0) * 128).astype(int), 0, T)
            b = np.clip(np.round(te * 128).astype(int), 0, T)
            wsw = (c[b] - c[a]) > (b - a) / 2
            Dd = (ed["r0f"].astype(float) - ed["r1f"].astype(float)) * np.where(wsw, -1.0, 1.0)[:, None]
            # decoder window j ends at reconstruction sample 8j + 32 and needs EEG < 8j + 48; the classifier decision at
            # hop index i (start a = 8i) needs EEG < a + 24. OFF = 4 (i = j + 4, a = 8j + 32) is the old conservative
            # alignment (the decoder evidence is 0.25 s older than it has to be); OFF = 3 (a = 8j + 24) uses exactly the
            # same EEG for both, i.e. the full 1-s budget (labels are stamped by the classifier convention, from a - 8).
            n = min(len(Dd), len(ec["r0"]) - OFF)
            assert np.allclose(te[:n], ec["t_end"][OFF:OFF + n] + (4 - OFF) * 0.25, atol=1e-3), r["key"]
            out[ds][r["key"]] = dict(X=np.column_stack([Dd[:n], (ec["r0"] - ec["r1"])[OFF:OFF + n]]), att=ec["att"][OFF:OFF + n],
                                     t_end=ec["t_end"][OFF:OFF + n])
    return out


def score(F, ds, mode):
    nF = next(iter(F[ds].values()))["X"].shape[1] - 1
    X = np.concatenate([e["X"] * np.where(e["att"] == 0, 1.0, -1.0)[:, None] for d in DS_KEYS if d != ds for e in F[d].values()])
    if mode == "dec_equal":
        w = np.r_[np.ones(nF) / nF, 0.0]
    elif mode == "clf":
        w = np.r_[np.zeros(nF), 1.0]
    else:
        idx = np.arange(nF) if mode == "dec_lda" else np.arange(nF + 1)
        w = np.zeros(nF + 1)
        w[idx] = np.linalg.solve(np.cov(X[:, idx].T), X[:, idx].mean(0))
        w /= np.abs(w).sum()

    def ev(e):
        d = e["X"] @ w
        k = len(d) // 40
        return dict(r0=d, r1=np.zeros_like(d), att=e["att"], t_end=e["t_end"], r0_10=d[:k * 40].reshape(k, 40).mean(1), r1_10=np.zeros(k),
                    att10=(e["att"][:k * 40].reshape(k, 40).mean(1) > 0.5).astype(np.int8), pre_switched=True)
    ev2 = {d: {k: ev(e) for k, e in F[d].items()} for d in DS_KEYS}
    r = S.score_dataset(ds, ev2, LA)
    return dict(ds=ds, mode=mode, H=r["H"], Acc=r["Acc"], SDT=r["SDT"], w=" ".join(f"{x:+.3f}" for x in w))


if __name__ == "__main__":
    rows = []
    for dec, clf in zip(sys.argv[1::2], sys.argv[2::2]):
        F = features(dec, clf)
        out = Parallel(n_jobs=int(os.environ.get("SCORE_JOBS", 3)))(delayed(score)(F, ds, m) for m in ("dec_equal", "dec_lda", "clf", "fused") for ds in DS_KEYS)
        for r in out:
            r.update(dec=dec, clf=clf)
        rows += out
        ref = lambda e: json.load(open(os.path.join(EXP, "results", f"{e}.json")))["causal"]["mean"]["H"]
        print(f"\n{dec}\n+ {clf}\n  stored H: decoder {ref(dec):.4f}, classifier {ref(clf):.4f}")
        d = pd.DataFrame(out)
        print(d.pivot(index="mode", columns="ds", values="H").assign(MEAN=d.groupby("mode").H.mean(), Acc=d.groupby("mode").Acc.mean(),
                                                                      SDT=d.groupby("mode").SDT.mean()).loc[["dec_equal", "dec_lda", "clf", "fused"]].round(4).to_string())
        print("  fused weights (decoder targets..., classifier):", {r["ds"]: r["w"] for r in out if r["mode"] == "fused"})
    pd.DataFrame(rows).to_csv(os.path.join(EXP, "results", "research", "fuse_evidence.csv"), index=False)
