"""Equivalence tests for the Python scorer port (MATLAB/Octave are not installed on this machine).

1. Hand-made cases whose expected output is derived by hand from computeSwitchLatency.m.
2. Randomised comparison against an independent brute-force implementation of the documented algorithm.
Writes tables/scorer_equivalence_tests.csv; exits non-zero on any failure.
"""
import os
import sys

import numpy as np
import pandas as pd

sys.path.insert(0, os.path.dirname(__file__))
from common import TAB  # noqa: E402
from scorer import aggregate, compute_switch_latency, score_subject  # noqa: E402

FS = 10          # hand cases: 10 Hz -> tSustain 0.5 s = 5 samples, searchWindow 100 s = 1000 samples
rows = []


def check(name, got, exp, note=""):
    ok = (np.isinf(exp) and np.isinf(got)) or (np.isnan(exp) and np.isnan(got)) or abs(got - exp) < 1e-9
    rows.append(dict(case=name, expected=exp, got=got, passed=bool(ok), note=note))


def seq(*parts):
    return np.concatenate([np.full(n, v, float) for v, n in parts])


# --- hand cases (one switch at i0 = 50 inside a 400-sample trial unless noted) ---
gt = seq((0, 50), (1, 350))
check("01 perfect decoder -> SDT 0", compute_switch_latency(gt, gt, [50], FS)[2][0], 0.0)
check("02 decoder 30 samples late -> 3.0 s", compute_switch_latency(seq((0, 80), (1, 320)), gt, [50], FS)[2][0], 3.0)
check("03 never switches -> undetected (Inf)", compute_switch_latency(seq((0, 400)), gt, [50], FS)[2][0], np.inf)
check("04 never switches -> ell = 0", compute_switch_latency(seq((0, 400)), gt, [50], FS)[1][0], 0.0)
check("05 already on new label before switch -> SDT 0 (never negative)",
      compute_switch_latency(seq((1, 400)), gt, [50], FS)[2][0], 0.0)
check("06 decoder switches 20 samples early -> SDT 0",
      compute_switch_latency(seq((0, 30), (1, 370)), gt, [50], FS)[2][0], 0.0)
d = seq((0, 55), (1, 1), (0, 34), (1, 310))
check("07 single-sample flicker ignored -> split at +40 -> 4.0 s", compute_switch_latency(d, gt, [50], FS)[2][0], 4.0)
d = seq((0, 60), (1, 3), (0, 1), (1, 336))
check("08 best split fails 5-sample sustain, resumes -> +14 -> 1.4 s",
      compute_switch_latency(d, gt, [50], FS)[2][0], 1.4, "score(+10) is max but run is 3 < 5; next valid +14")
check("09 ell for 3.0 s = exp(-3/60)", compute_switch_latency(seq((0, 80), (1, 320)), gt, [50], FS)[1][0],
      np.exp(-3 / 60))
gt2 = seq((0, 50), (1, 1100))
check("10 switch exactly at t0+100 s -> SDT 100", compute_switch_latency(seq((0, 1050), (1, 100)), gt2, [50], FS)[2][0],
      100.0)
check("11 switch at t0+100 s + 1 sample -> undetected",
      compute_switch_latency(seq((0, 1051), (1, 99)), gt2, [50], FS)[2][0], np.inf)
d = np.r_[np.full(50, 0.0), np.full(20, np.nan), np.full(330, 1.0)]
check("12 NaN decisions count as disagreement -> split at +20 -> 2.0 s",
      compute_switch_latency(d, gt, [50], FS)[2][0], 2.0)
# trial clipping: trial 0 = samples 0..99 (switch at 50), trial 1 = 100..399
gtt = np.r_[seq((0, 50), (1, 50)), seq((0, 300))]
tr = np.r_[np.zeros(100), np.ones(300)]
d = np.r_[seq((0, 100)), seq((1, 300))]
check("13 decoder only turns over in the next trial -> undetected (clipped)",
      compute_switch_latency(d, gtt, [50], FS, trial_of=tr)[2][0], np.inf)
gte = np.r_[seq((0, 97), (1, 3)), seq((1, 300))]
d = np.r_[seq((0, 97), (1, 3)), seq((1, 300))]
check("14 switch 3 samples before trial end, sustain read from NEXT trial -> detected SDT 0",
      compute_switch_latency(d, gte, [97], FS, trial_of=tr)[2][0], 0.0,
      "MATLAB extHi is not clipped to the trial: sustain may use the next trial's decisions")
d = np.r_[seq((0, 97), (1, 3)), seq((0, 300))]
check("15 same, next trial decodes old label -> undetected",
      compute_switch_latency(d, gte, [97], FS, trial_of=tr)[2][0], np.inf)
# two switches within 100 s
gt3 = seq((0, 50), (1, 200), (0, 750))
L, ell, sdt, tau, nov = compute_switch_latency(seq((0, 60), (1, 200), (0, 740)), gt3, [50, 250], FS)
check("16 two switches 20 s apart: first switch UNDETECTED", sdt[0], np.inf,
      "late split (old label for the remaining 74 s of the window) outscores the true split, fails sustain, "
      "and the search resumes past the window end")
check("17 two switches: second SDT 1.0", sdt[1], 1.0)
check("18 two switches: nOverlap = 1", nov, 1.0, "the first search window [t0, t0+100 s] contains the second switch")
L, ell, sdt, tau, nov = compute_switch_latency(seq((0, 1000)), gt3, [50, 250], FS)
check("19 two switches, constant decoder: first undetected", sdt[0], np.inf)
check("20 two switches, constant decoder: second (1->0) SDT 0 (old label never shown after)", sdt[1], 0.0,
      "a decoder stuck on label 0 'detects' the 1->0 switch instantly")
# oracle (perfect) decoder with a reverting second switch: detected only if the gap >= searchWindow/2
for gap_s, exp in ((40, np.inf), (49.9, np.inf), (50, 0.0), (60, 0.0)):
    g = int(gap_s * FS)
    gto = seq((0, 50), (1, g), (0, 1200))
    check(f"O oracle decoder, reverting switch {gap_s} s later: first-switch SDT", 
          compute_switch_latency(gto, gto, [50, 50 + g], FS)[2][0], exp,
          "perfect decoder is charged Inf when the next (reverting) switch is < 50 s away")
# tie-breaking: earliest maximum
d = seq((0, 50), (1, 5), (0, 5), (1, 340))
check("21 tie between +0 and +10 splits -> earliest (+0)", compute_switch_latency(d, gt, [50], FS)[2][0], 0.0)
# rounding at 128 Hz: sustain = 64 samples
gt128 = seq((0, 1000), (1, 20000))
d = seq((0, 1000), (1, 63), (0, 1), (1, 19936))
check("22 128 Hz: 63-sample run fails 64-sample sustain -> +64 (0.5 s)",
      compute_switch_latency(d, gt128, [1000], 128)[2][0], 64 / 128)
# score_subject / aggregate
gs = np.r_[seq((0, 50), (1, 350)), seq((1, 400))]
ts = np.r_[np.zeros(400), np.ones(400)]
ps = np.r_[seq((0, 80), (1, 320)), seq((0, 400))]
s = score_subject(ps, gs, ts, fs=FS)
check("23 score_subject: boundary change not a switch", s["nSwitches"], 1.0)
check("24 score_subject: accuracy % (370 of 800 samples right)", s["acc"], 100 * 370 / 800)
agg = aggregate([dict(acc=68.4, L=0.7172, sdt=18.53, nSwitches=1, nUndetected=0)])
check("25 aggregate H = 2AL/(A+L)", agg["H"], 2 * 0.684 * 0.7172 / (0.684 + 0.7172))
agg = aggregate([dict(acc=60, L=np.nan, sdt=np.nan, nSwitches=0, nUndetected=0),
                 dict(acc=80, L=0.5, sdt=10, nSwitches=2, nUndetected=0)])
check("26 aggregate: subject without switches excluded from L", agg["L"], 0.5)
check("27 aggregate: Acc still averages both", agg["Acc"], 70.0)
agg = aggregate([dict(acc=50, L=0.0, sdt=np.inf, nSwitches=1, nUndetected=1)] * 3)
check("28 aggregate: all undetected -> H = 0", agg["H"], 0.0)
check("29 aggregate: SDT median over subjects Inf", agg["SDT"], np.inf)


# --- independent brute-force reference ---
def brute(decision, att, sw, fs, trial_of, searchWindow, tSustain):
    n_all = len(decision)
    nS = int(np.floor(searchWindow * fs + 0.5))
    nU = max(1, int(np.floor(tSustain * fs + 0.5)))
    out = []
    for i0 in sw:
        old, new = att[i0 - 1], att[i0]
        lo, hi = i0, min(n_all - 1, i0 + nS)
        if trial_of is not None:
            idx = np.flatnonzero(trial_of == trial_of[i0])
            lo, hi = max(lo, idx[0]), min(hi, idx[-1])
        scores = {t: sum(decision[j] == old for j in range(lo, t)) + sum(decision[j] == new for j in range(t, hi + 1))
                  for t in range(lo, hi + 1)}
        lower, found = lo, None
        while lower <= hi:
            best = max(range(lower, hi + 1), key=lambda t: (scores[t], -t))
            if best + nU - 1 <= n_all - 1 and all(decision[j] == new for j in range(best, best + nU)):
                found = best
                break
            lower = best + 1
        out.append(np.inf if found is None else abs(found - i0) / fs)
    return np.array(out)


rng = np.random.default_rng(0)
n_rand, n_fail = 3000, 0
for it in range(n_rand):
    T = int(rng.integers(20, 90))
    fs = float(rng.choice([1, 2, 4]))
    sw_ = rng.uniform(2, 25)
    ts_ = float(rng.choice([0.5, 1.0, 2.0]))
    nt = int(rng.integers(1, 3))
    trial = np.sort(rng.integers(0, nt, T))
    att = np.zeros(T)
    lab = int(rng.integers(0, 2))
    for t in range(T):
        if t > 0 and trial[t] == trial[t - 1] and rng.random() < 0.08:
            lab = 1 - lab
        att[t] = lab
    dec = np.where(rng.random(T) < rng.uniform(0.5, 0.95), att, 1 - att)
    dec = np.where(rng.random(T) < 0.05, np.nan, dec)
    sws = [t for t in range(1, T) if att[t] != att[t - 1] and trial[t] == trial[t - 1]]
    if not sws:
        continue
    use_trial = trial if rng.random() < 0.7 else None
    a = compute_switch_latency(dec, att, sws, fs, trial_of=use_trial, searchWindow=sw_, tSustain=ts_)[2]
    b = brute(dec, att, sws, fs, use_trial, sw_, ts_)
    if not np.array_equal(a, b):
        n_fail += 1
rows.append(dict(case=f"R random vs brute force ({n_rand} sequences)", expected=0, got=n_fail, passed=n_fail == 0,
                 note="independent O(n^2) implementation of the documented split search"))
df = pd.DataFrame(rows)
df.to_csv(os.path.join(TAB, "scorer_equivalence_tests.csv"), index=False)
print(df.to_string())
print(f"PASSED {df.passed.sum()}/{len(df)}")
sys.exit(0 if df.passed.all() else 1)
