"""Lookahead unit test for the full causal pipeline (raw 128 Hz arrays -> per-sample labels).

Pipeline: common57 by name -> causal HP 0.5 / BP 1-9 / AA 12 Hz (sosfilt, zi-initialised) -> 32 Hz -> CAR ->
running robust z (EEG and envelopes) -> drop the 1-s warm-up -> LODO backward decoder (lags 0-500 ms) ->
1-s correlation windows every 0.25 s -> causal integrator -> labels, each decision stamped from
t_end + L - budget (budget = 1 s).
Test: for several t, add large noise to ALL inputs (EEG and both envelopes) at samples strictly after
t + 1 s and assert that labels[0..t] are unchanged. Negative controls, which must be flagged: (a) an illegal
2-s budget, (b) zero-phase (sosfiltfilt) filtering with the legal budget. A 1.25-s budget was NOT flagged in a
first version: a 0.25-s leak touches only the last quarter-second of one lag window, and the running z-score
clips the perturbation at +-5, so small leaks can escape this test (it has limited sensitivity).
Writes tables/lookahead_test.csv; exits non-zero if the legal pipeline fails.
"""
import os
import sys

import numpy as np
import pandas as pd

sys.path.insert(0, os.path.dirname(__file__))
from c2_decoders import lagged  # noqa: E402
from c3_windows import win_corr_sliding  # noqa: E402
from common import CACHE, FS, TAB, car, filter_chain, load_env, load_eeg, montage_idx, running_z, trial_index  # noqa: E402
from e1_switch import integ_argmax, integ_hmm, integ_ma  # noqa: E402

FSO = 32


def expand_b(dec, t_end, L, T, guess, budget):
    lab = np.full(T, guess, float)
    s0 = np.clip(np.ceil((t_end + L - budget) * FS).astype(int), 0, T)
    for j in range(len(dec)):
        e = s0[j + 1] if j + 1 < len(dec) else T
        lab[s0[j]:e] = dec[j]
    return lab


def pipeline_labels(raw, env, row, dvec, integ, p, budget=1.0, Lsamp=16, variant="c19"):
    x = raw[:, montage_idx(row, "common57")]
    y, _ = filter_chain(x, variant)
    e, _ = filter_chain(env, variant)
    y = running_z(car(y), FSO)
    e = running_z(e, FSO)
    k = FSO
    y, e = y[k:], e[k:]
    yh = lagged(y.astype(np.float32), Lsamp) @ dvec.astype(np.float32)
    r, st = win_corr_sliding(yh.astype(float), e[: len(yh)], FSO, FSO // 4)
    t_end = 1.0 + (st + FSO) / FSO
    return expand_b(integ(r[:, 0] - r[:, 1], p), t_end, Lsamp / FSO, len(raw), 0, budget)


if __name__ == "__main__":
    ti = trial_index()
    row = ti[ti.ds == "AVGC"].iloc[0]
    raw = np.asarray(load_eeg(row["key"]), dtype=np.float64)
    env = load_env(row["key"]).astype(np.float64)
    dvec = np.load(os.path.join(CACHE, "recon", "c19-common57-car", "lodo_pool", "_decoder_AVGC.npz"))["0-500ms"]
    integs = [("argmax", integ_argmax, {}), ("ma_10s", integ_ma, dict(mem_s=10)),
              ("hmm_p0.99", integ_hmm, dict(p_stay=0.99, mu=0.03, sd=0.2))]
    rng = np.random.default_rng(0)
    rows = []
    for budget, variant, legal in ((1.0, "c19", True), (2.0, "c19", False), (1.0, "z19", False)):
        for name, fn, p in integs:
            base = pipeline_labels(raw, env, row, dvec, fn, p, budget, variant=variant)
            for t in (5.0, 30.0, 150.0, 299.0, 301.0, 450.0, 590.0):
                i0 = int(np.floor((t + 1.0) * FS)) + 1              # first perturbed sample: strictly after t + 1 s
                r2, e2 = raw.copy(), env.copy()
                r2[i0:] += 1e3 * rng.standard_normal(r2[i0:].shape) * raw.std()
                e2[i0:] = rng.standard_normal(e2[i0:].shape) * env.std() * 10
                pert = pipeline_labels(r2, e2, row, dvec, fn, p, budget, variant=variant)
                upto = int(np.floor(t * FS)) + 1
                changed_before = int(np.sum(base[:upto] != pert[:upto]))
                changed_after = int(np.sum(base[upto:] != pert[upto:]))
                rows.append(dict(budget_s=budget, filters=("causal" if variant == "c19" else "zero-phase"), legal=legal, integrator=name, t_s=t, n_labels_checked=upto,
                                 n_changed_up_to_t=changed_before, n_changed_after_t=changed_after,
                                 passed=changed_before == 0))
    df = pd.DataFrame(rows)
    df.to_csv(os.path.join(TAB, "lookahead_test.csv"), index=False)
    print(df.to_string())
    legal_ok = df[df.legal].passed.all()
    control_caught = (~df[~df.legal].passed).any()
    print(f"LEGAL pipeline (1 s budget): {'PASS' if legal_ok else 'FAIL'} "
          f"({int(df[df.legal].passed.sum())}/{int(df.legal.sum())} checks)")
    for (b, f), g in df[~df.legal].groupby(["budget_s", "filters"]):
        print(f"NEGATIVE CONTROL ({f} filters, {b} s budget) flagged in {int((~g.passed).sum())}/{len(g)} checks")
    control_caught = all((~g.passed).any() for _, g in df[~df.legal].groupby(["budget_s", "filters"]))
    sys.exit(0 if (legal_ok and control_caught) else 1)
