"""Switch-detection scoring of one experiment (all 5 LODO folds must exist).

Per held-out dataset D:
  * evidence d = r(col0) - r(col1), 1-s windows at 0.25-s hop, from the decoder that never saw D
  * SYNTHETIC switches with the same generator, seed and trial order as the full-corpus EDA (e1_switch.py),
    so every experiment is scored on identical switch schedules
  * integrator: 2-state HMM, p_stay = 0.998 per 0.25-s step; Gaussian emissions (mu, sd) fitted on the OTHER four
    datasets' out-of-fold evidence of the same experiment (no test data)
  * labels stamped from t_end + lookahead - 1 s (the 1-s budget), random guess before the first decision
  * official scorer (verified Python port): Acc, SDT, L, H per subject, aggregated per dataset
  * null: the same pipeline on sign-randomised evidence
Plus plain decoding: accuracy of non-overlapping 1-s and 10-s windows (median over subjects) and SNR1.
"""
import os
import pickle
import zlib

import numpy as np

from common_exp import CFG, EXP, LAB, fold_file, rows_of
from common import CACHE as EDA_CACHE, DS_KEYS, FS as FS128, SEED
from e1_switch import expand, integ_hmm, synth_trial
from scorer import aggregate, fast_score_subject

S = CFG["switch"]


SCHED = int(os.environ.get("SCHEDULE_OFFSET", 0))        # seed offset of the synthetic-switch schedule (schedule_noise.py); 0 = the schedule of every experiment

def load_folds(exp, mode):
    ev = {}
    info = {}
    for ds in DS_KEYS:
        with open(fold_file(exp, ds), "rb") as fh:
            f = pickle.load(fh)
        ev[ds] = f["evidence"][mode]
        info[ds] = f["info"]
    return ev, info


def plain_metrics(ds, evd):
    rows = rows_of(ds)
    per = {}
    for _, r in rows.iterrows():
        e = evd[r["key"]]
        d = (e["r0"] - e["r1"])[::4]                     # non-overlapping 1-s windows
        a = e["att"][::4]
        sgn = np.where(a == 0, 1.0, -1.0)
        d10 = e["r0_10"] - e["r1_10"]
        s10 = np.where(e["att10"] == 0, 1.0, -1.0)
        p = per.setdefault(r["subj_uid"], [[], [], []])
        p[0].append(d * sgn)
        p[1].append((d10 * s10) > 0)
    acc1, acc10, snr = [], [], []
    for u, (dd, c10, _) in per.items():
        dd = np.concatenate(dd)
        acc1.append(np.mean(dd > 0))
        snr.append(dd.mean() / (dd.std() + 1e-12))
        c10 = np.concatenate(c10)
        if len(c10):
            acc10.append(np.mean(c10))
    return dict(acc1=float(np.median(acc1)), acc10=float(np.median(acc10)) if acc10 else np.nan, snr1=float(np.median(snr)))


def score_dataset(ds, ev, lookahead, null=False, emis=None, p_stay=None):
    """emis=(mu, sd) / p_stay override the emissions fitted on the other four datasets / the config p_stay
    (used for the end-to-end trained CRF, whose evidence is already a log-likelihood ratio)."""
    train = [d for d in DS_KEYS if d != ds]
    A = []
    for d in train:
        for e in ev[d].values():
            A.append((e["r0"] - e["r1"]) * np.where(e["att"] == 0, 1.0, -1.0))
    A = np.concatenate(A)
    mu, sd = (float(A.mean()), float(A.std())) if emis is None else emis
    rng = np.random.default_rng(SEED + SCHED + DS_KEYS.index(ds))   # identical schedule to the EDA (SCHED = 0)
    per = {}
    for _, r in rows_of(ds).iterrows():
        T = int(r["n"])
        e = ev[ds][r["key"]]
        lab = np.load(os.path.join(EDA_CACHE, "cnd", f"{r['key']}.npz"))
        att = lab["att_col"][:T].astype(int)
        d = (e["r0"] - e["r1"]).astype(float)
        t_end = e["t_end"].astype(float)
        st, d_syn, _ = synth_trial(r["key"], T, d, t_end, rng)
        if e.get("pre_switched"):                 # direct classifier: the switch was applied to its INPUT (same schedule)
            d_syn = d
        guess = int(rng.integers(0, 2))
        if null:
            g = np.random.default_rng(SEED + zlib.crc32(r["key"].encode()))
            d_syn = np.abs(d_syn) * g.choice([-1.0, 1.0], len(d_syn))
        dec = integ_hmm(d_syn, dict(p_stay=p_stay or S["p_stay"], mu=mu, sd=sd))
        labs = expand(dec, t_end, lookahead, T, guess)
        per.setdefault(r["subj_uid"], []).append((labs, np.where(st, 1 - att, att)))
    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)])
        res.append(fast_score_subject(pred, gt, trial, fs=FS128))
    a = aggregate(res)
    return dict(Acc=a["Acc"], SDT=a["SDT"], L=a["L"], H=a["H"], nSwitches=a["nSwitches"], nUndetected=a["nUndetected"],
                miss_rate=a["nUndetected"] / max(a["nSwitches"], 1), emis_mu=mu, emis_sd=sd)


def lda_weights(ev, ds):
    """Target weights for held-out dataset ds: w = Sigma^-1 mu of the signed per-target evidence (r0f - r1f) of the
    OTHER four datasets' out-of-fold folds (no test data), normalised to sum |w| = 1. Optimal linear combination for
    Gaussian evidence (= a 2-state HMM with multivariate Gaussian emissions sharing one covariance)."""
    X = np.concatenate([(e["r0f"].astype(float) - e["r1f"].astype(float)) * np.where(e["att"] == 0, 1.0, -1.0)[:, None]
                        for d in DS_KEYS if d != ds for e in ev[d].values()])
    w = np.linalg.solve(np.cov(X.T), X.mean(0))
    return w / np.abs(w).sum()


def weighted_evidence(ev, w):
    """Evidence with r0 / r1 recombined from the per-target correlations (1-s windows; the 10-s windows of acc10 keep
    the equal-weight mean, their per-target values are not stored)."""
    return {d: {k: {**e, "r0": e["r0f"].astype(float) @ w, "r1": e["r1f"].astype(float) @ w} for k, e in ev[d].items()}
            for d in DS_KEYS}


def score_experiment(exp, mode, lookahead, weights="equal"):
    """weights: 'equal' = mean over targets (default) | 'lda' = lda_weights() per held-out dataset (multi-target only)
    | 'crf' = the unary weights v learned END-TO-END in that fold (DNNDec.fit_sequence, fold info['crf']): the evidence
    sum_f v_f (r0_f - r1_f) is a log-likelihood ratio, used as such (emissions mu 0.5, sd 1 <=> LLR = d)."""
    ev0, info = load_folds(exp, mode)
    per_ds, W = {}, {}
    for ds in DS_KEYS:
        ev, kw = ev0, {}
        if weights == "lda":
            W[ds] = lda_weights(ev0, ds)
            ev = weighted_evidence(ev0, W[ds])
        elif weights == "crf":
            W[ds] = np.array(info[ds]["crf"]["v"])
            ev, kw = weighted_evidence(ev0, W[ds]), dict(emis=(0.5, 1.0), p_stay=info[ds]["crf"]["p_stay"])
        r = score_dataset(ds, ev, lookahead, **kw)
        n = score_dataset(ds, ev, lookahead, null=True, **kw)
        r.update(null_L=n["L"], null_H=n["H"], **plain_metrics(ds, ev[ds]))
        per_ds[ds] = r
    keys = ["Acc", "SDT", "L", "H", "miss_rate", "null_L", "null_H", "acc1", "acc10", "snr1"]
    mean = {k: float(np.mean([per_ds[d][k] for d in DS_KEYS])) for k in keys}
    return dict(per_dataset=per_ds, mean=mean, info=info,
                **({"target_weights": {d: [float(x) for x in w] for d, w in W.items()}} if W else {}))
