"""B5 (H8): can slow-drift features alone predict the trial label (attended side at onset)?

Features per trial on the common57 montage (matched by name), all from the raw 128 Hz data:
  per-channel mean (DC), linear drift slope (units/min), log power below 1 Hz (variance of the
  linearly detrended 1-s block means, i.e. content below ~0.5 Hz).
Trial index / order is NOT a feature. Logistic regression (standardised, L2), evaluated
  LOTO   within subject, balanced leave-pair-out (one left + one right trial held out)
  LOSO   within dataset
Chance = 0.5 (balanced held-out pairs for LOTO; labels ~balanced within each dataset for LOSO).
Writes tables/drift_classifier_per_subject.csv, tables/drift_classifier_summary.csv
"""
import os
import sys

import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy import stats
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

sys.path.insert(0, os.path.dirname(__file__))
from common import CACHE, DS_KEYS, FS, TAB, boot_ci, get_logger, load_eeg, montage_idx, trial_index  # noqa: E402

log = get_logger("b3_drift_classifier")


def feats(row):
    p = os.path.join(CACHE, "drift", f"{row['key']}.npy")
    if os.path.exists(p):
        return np.load(p)
    x = np.asarray(load_eeg(row["key"])[:, montage_idx(row, "common57")], dtype=np.float64)
    T = len(x)
    t = (np.arange(T) / FS / 60.0)
    t = t - t.mean()
    mean = x.mean(0)
    slope = (t[:, None] * (x - mean)).sum(0) / (t ** 2).sum()
    nb = T // FS
    B = x[: nb * FS].reshape(nb, FS, -1).mean(1)
    tb = np.arange(nb) - (nb - 1) / 2
    B = B - B.mean(0) - np.outer(tb, (tb[:, None] * (B - B.mean(0))).sum(0) / (tb ** 2).sum())
    f = np.r_[mean, slope, np.log(B.var(0) + 1e-12)].astype(np.float32)
    os.makedirs(os.path.dirname(p), exist_ok=True)
    np.save(p, f)
    return f


def clf():
    return make_pipeline(StandardScaler(), LogisticRegression(C=0.1, max_iter=2000))


if __name__ == "__main__":
    ti = trial_index()
    X = np.array(Parallel(n_jobs=2)(delayed(feats)(r) for _, r in ti.iterrows()))
    y = ti.label.str.lower().str[0].map({"l": 0, "r": 1}).values
    rows = []
    for ds in DS_KEYS:
        dm = (ti.ds == ds).values
        subs = ti.subject.values
        for s in np.unique(subs[dm]):
            sm = dm & (subs == s)
            idx = np.flatnonzero(sm)
            # within-subject leave-pair-out (one left + one right trial held out; up to 60 random pairs).
            # Plain leave-one-trial-out is biased BELOW 0.5 with balanced labels (the held-out class is
            # the training minority), so the balanced variant is used as the "LOTO" scheme here.
            rng = np.random.default_rng(int(s))
            L_, R_ = idx[y[idx] == 0], idx[y[idx] == 1]
            pairs = [(a, b) for a in L_ for b in R_]
            if len(pairs) > 60:
                pairs = [pairs[i] for i in rng.choice(len(pairs), 60, replace=False)]
            pr = []
            for a, b in pairs:
                tr = idx[(idx != a) & (idx != b)]
                if len(np.unique(y[tr])) < 2:
                    continue
                pp = clf().fit(X[tr], y[tr]).predict(X[[a, b]])
                pr += [float(pp[0] == y[a]), float(pp[1] == y[b])]
            rows.append(dict(scheme="LOTO", ds=ds, subject=s, acc=np.mean(pr) if pr else np.nan, n=len(idx)))
            # LOSO within dataset
            tr = dm & (subs != s)
            p = clf().fit(X[tr], y[tr]).predict(X[sm])
            rows.append(dict(scheme="LOSO", ds=ds, subject=s, acc=float((p == y[sm]).mean()), n=len(idx)))
    df = pd.DataFrame(rows)
    df.to_csv(os.path.join(TAB, "drift_classifier_per_subject.csv"), index=False)
    out = []
    for (sch, ds), g in df.groupby(["scheme", "ds"]):
        m, lo, hi = boot_ci(g.acc.values)
        w = stats.wilcoxon(g.acc - 0.5).pvalue if (g.acc != 0.5).sum() > 5 else np.nan
        out.append(dict(scheme=sch, ds=ds, n_subjects=len(g), n_trials=int(g.n.sum()), median_acc=m, ci_lo=lo,
                        ci_hi=hi, mean_acc=g.acc.mean(), wilcoxon_vs_0p5_p=w))
    out = pd.DataFrame(out)
    out.to_csv(os.path.join(TAB, "drift_classifier_summary.csv"), index=False)
    log.info("\n" + out.to_string())
