"""Phase E on GENUINE switches: the 99 KUL-AV-GC direction switches (t = 300 s), scored with direction
evidence from spatial decoders trained on the other four datasets only (d3: FBCSP-LDA and Riemann-LR, 1-s
windows, 0.25-s hop, causal filters -> no EEG after the window end, L = 0).
Emissions for the HMM integrators are fitted on the training datasets' own out-of-fold (LODO) decision values.
Ground truth: attended side per 128 Hz sample (sign of the CND attended azimuth); 0 = left, 1 = right.
Writes tables/spatial_switch_results.csv, tables/spatial_switch_per_subject.csv
"""
import os
import sys

import numpy as np
import pandas as pd

sys.path.insert(0, os.path.dirname(__file__))
from common import CACHE, FS, SEED, TAB, get_logger, load_labels, trial_index  # noqa: E402
from e1_switch import HOP, S, configs, expand, running_sd  # noqa: E402
from scorer import aggregate, fast_score_subject  # noqa: E402
import zlib  # noqa: E402

log = get_logger("e2_spatial_switch")

if __name__ == "__main__":
    ti = trial_index()
    dec = pd.read_parquet(os.path.join(CACHE, "spatial_decisions.parquet"))
    rows, srows = [], []
    for model in ("fbcsp", "riemann"):
        tr = dec[(dec.model == model) & (dec.kind == "1") & (dec.scheme == "LODO") & (dec.ds != "AVGC")]
        sgn = np.where(tr.y.values == 0, 1.0, -1.0)
        d = -tr.dv.values
        zz = np.concatenate([(-g.dv.values) / running_sd(-g.dv.values, 60.0 / HOP) for _, g in tr.groupby("key", sort=False)])
        sg2 = np.concatenate([np.where(g.y.values == 0, 1.0, -1.0) for _, g in tr.groupby("key", sort=False)])
        emis = dict(mu=float(np.mean(d * sgn)), sd=float(np.std(d * sgn)), mu_z=float(np.mean(zz * sg2)))
        trials = []
        for _, r in ti[ti.ds == "AVGC"].iterrows():
            z = np.load(os.path.join(CACHE, "evidence_dir", model, f"{r['key']}.npz"))
            lab = load_labels(r["key"])
            T = int(r["n"])
            trials.append(dict(key=r["key"], subj=r["subj_uid"], T=T, d=z["d"].astype(float), t_end=z["t_end"].astype(float),
                               gt=(lab["att_az"][:T] > 0).astype(int),
                               guess=int(np.random.default_rng(SEED + zlib.crc32(r["key"].encode())).integers(0, 2))))
        for name, fn, p in configs(emis):
            for null in (False, True):
                per = {}
                for t in trials:
                    dd = t["d"]
                    if null:
                        dd = np.abs(dd) * np.random.default_rng(SEED + zlib.crc32(t["key"].encode())).choice([-1.0, 1.0], len(dd))
                    labs = expand(fn(dd, p), t["t_end"], 0.0, t["T"], t["guess"])
                    per.setdefault(t["subj"], []).append((labs, t["gt"]))
                res = []
                for subj, lst in per.items():
                    pred = np.concatenate([a for a, _ in lst])
                    gt = np.concatenate([b for _, b in lst])
                    trial = np.concatenate([np.full(len(a), i) for i, (a, _) in enumerate(lst)])
                    rr = fast_score_subject(pred, gt, trial, fs=FS, searchWindow=S["search_window_s"],
                                            tSustain=S["t_sustain_s"], tau0=S["tau0_s"])
                    rr["subject"] = subj
                    res.append(rr)
                    if not null:
                        srows.append(dict(model=model, integrator=name, subject=subj, acc=rr["acc"], L=rr["L"], sdt=rr["sdt"],
                                          n_switches=rr["nSwitches"], n_undetected=rr["nUndetected"]))
                a = aggregate(res)
                rows.append(dict(model=model, integrator=name, null=null, emis=str(emis),
                                 **{k: a[k] for k in ("Acc", "SDT", "L", "H", "nSwitches", "nUndetected")}))
        log.info(f"{model}: emissions {emis}")
    df = pd.DataFrame(rows)
    df.to_csv(os.path.join(TAB, "spatial_switch_results.csv"), index=False)
    pd.DataFrame(srows).to_csv(os.path.join(TAB, "spatial_switch_per_subject.csv"), index=False)
    for model in ("fbcsp", "riemann"):
        g = df[(df.model == model) & ~df.null].sort_values("H", ascending=False)
        n = df[(df.model == model) & df.null]
        log.info(f"{model} GENUINE KUL-AV-GC direction switches, top-5 by H:\n"
                 + g.head(5)[["integrator", "Acc", "SDT", "L", "H", "nSwitches", "nUndetected"]].round(3).to_string()
                 + f"\n null L median {n.L.median():.3f} (range {n.L.min():.3f}-{n.L.max():.3f}), null Acc median {n.Acc.median():.2f}")
