"""Derive a no-carry EA prep (config preps with ea / ea_prior / ea_n0, e.g. eaP_n5_t60) for the external evaluation sets
from their 'mat' cache (58 ch, CAR, full-trial z-score, trimmed; no EA): the causal EA of prepare_data is applied per
trial, exactly as for the corpus (prepare_data.build). No state is carried across trials (test rule 6.3).
usage: python derive_prep.py PREP [AASD Carta2026 ...]"""
import os
import sys

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "decoder_lodo"))
from prepare_data import CFG, causal_ea, ea_prior  # noqa: E402

if __name__ == "__main__":
    prep, sets = sys.argv[1], sys.argv[2:] or ["AASD", "Carta2026"]
    P = CFG["preps"][prep]
    assert P.get("ea") == "causal" and not P.get("ea_carry"), prep
    for ds in sets:
        src, dst = os.path.join(HERE, ds, "cache", "mat"), os.path.join(HERE, ds, "cache", prep)
        os.makedirs(dst, exist_ok=True)
        fs_ = sorted(f for f in os.listdir(src) if f.endswith(".npz"))
        for f in fs_:
            z = dict(np.load(os.path.join(src, f)))
            x = z["eeg"].astype(np.float64)
            z["eeg"] = causal_ea(x, CFG["fs"], tau_s=P.get("ea_tau", 60.0), R0=ea_prior(P, x), n0=P.get("ea_n0"),
                                 shrink=P.get("ea_shrink", 0.1)).astype(np.float32)
            np.savez(os.path.join(dst, f), **z)
        print(f"{ds} [{prep}]: {len(fs_)} trials")
