"""Line-by-line Python port of the official MATLAB scorer (baselines/matlab_scoring).

computeSwitchLatency.m  -> compute_switch_latency()
scorePredictions.m      -> score_subject() / aggregate()      (per-subject scoring + cohort aggregation)
defaultLatencyOpts.m    -> DEFAULTS
Indices are 0-based here; every MATLAB 1-based expression is translated explicitly (see comments).
MATLAB round() rounds half away from zero; Python's round() does not, so _mround() is used.
"""
from __future__ import annotations

import numpy as np

DEFAULTS = dict(searchWindow=100.0, tSustain=0.5, tUndetected=np.inf, tau0=60.0)


def _mround(x):
    return int(np.sign(x) * np.floor(abs(x) + 0.5))


def compute_switch_latency(decision, att_label, switch_samples, fs, trial_of=None, **opts):
    """Returns L, ell, sdt, tau_star (0-based sample index or NaN), n_overlap.

    decision, att_label: per-sample labels (any integer coding; NaN = no decision).
    switch_samples: 0-based indices i0 of the FIRST sample carrying the new label (within-trial only).
    """
    o = dict(DEFAULTS)
    o.update(opts)
    decision = np.asarray(decision, float).ravel()
    att_label = np.asarray(att_label, float).ravel()
    sw = np.asarray(switch_samples, int).ravel()
    nSamp = len(decision)
    nSw = len(sw)
    ell = np.full(nSw, np.nan)
    sdt = np.full(nSw, np.nan)
    tau_star = np.full(nSw, np.nan)
    n_overlap = 0
    if nSw == 0:
        return np.nan, ell, sdt, tau_star, 0
    nSearch = _mround(o["searchWindow"] * fs)
    nSustain = max(1, _mround(o["tSustain"] * fs))
    restrict = trial_of is not None
    if restrict:
        trial_of = np.asarray(trial_of).ravel()
        if len(trial_of) != nSamp:
            raise ValueError("trial_of length mismatch")
        edges = np.r_[0, np.flatnonzero(np.diff(trial_of) != 0) + 1, nSamp]
        t_start = np.empty(nSamp, int)
        t_end = np.empty(nSamp, int)
        for b in range(len(edges) - 1):
            t_start[edges[b]:edges[b + 1]] = edges[b]
            t_end[edges[b]:edges[b + 1]] = edges[b + 1] - 1
    for k in range(nSw):
        i0 = sw[k]
        new_lab = att_label[i0]
        old_lab = att_label[i0 - 1]
        lo = max(0, i0)                                   # MATLAB lo = max(1, i0)
        hi = min(nSamp - 1, i0 + nSearch)                 # MATLAB hi = min(nSamp, i0 + nSearch)
        if restrict:
            lo = max(lo, t_start[i0])
            hi = min(hi, t_end[i0])
        seg = decision[lo:hi + 1]
        n = len(seg)
        if k < nSw - 1 and sw[k + 1] <= hi:
            n_overlap += 1
        prefix_old = np.r_[0, np.cumsum(seg == old_lab)]          # prefix_old[j] = matches in seg[0:j]
        suf_new = np.cumsum((seg == new_lab)[::-1])[::-1]          # suf_new[t]   = matches in seg[t:]
        score = prefix_old[:n] + suf_new[:n]
        suf_arg = np.zeros(n, int)
        suf_arg[n - 1] = n - 1
        for i in range(n - 2, -1, -1):
            suf_arg[i] = i if score[i] >= score[suf_arg[i + 1]] else suf_arg[i + 1]
        ext_hi = min(nSamp - 1, lo + n - 1 + nSustain - 1)        # NOT clipped to the trial (as in MATLAB)
        is_new = decision[lo:ext_hi + 1] == new_lab
        run_new = np.zeros(len(is_new) + 1, int)
        for i in range(len(is_new) - 1, -1, -1):
            if is_new[i]:
                run_new[i] = run_new[i + 1] + 1
        tau = None
        lower = 0
        while lower <= n - 1:
            cand = suf_arg[lower]
            if lo + cand + nSustain - 1 <= nSamp - 1 and run_new[cand] >= nSustain:
                tau = cand
                break
            lower = cand + 1
        if tau is None:
            sdt[k] = o["tUndetected"]
        else:
            tau_star[k] = lo + tau
            sdt[k] = abs(tau_star[k] - i0) / fs
        ell[k] = np.exp(-sdt[k] / o["tau0"])
    L = float(np.nanmedian(ell)) if np.any(np.isfinite(ell)) or np.any(ell == 0) else np.nan
    return L, ell, sdt, tau_star, n_overlap


def score_subject(pred, gt, trial, fs=128, **latency_opts):
    """scorePredictions.m inner loop for one subject (labels in the file's 0-based coding)."""
    pred = np.asarray(pred)
    gt = np.asarray(gt)
    trial = np.asarray(trial)
    if len(pred) != len(gt):
        raise ValueError("length mismatch")
    acc = float(np.mean(pred == gt) * 100)
    is_change = np.r_[False, np.diff(gt) != 0]
    is_new_trial = np.r_[False, np.diff(trial) != 0]
    switch = np.flatnonzero(is_change & ~is_new_trial)
    n_boundary = int(np.sum(is_change & is_new_trial))
    L, ell, sdt, _, nov = compute_switch_latency(pred, gt, switch, fs, trial_of=trial, **latency_opts)
    return dict(acc=acc, sdt=float(np.median(sdt)) if len(sdt) else np.nan, L=L, nSwitches=len(switch),
                nUndetected=int(np.sum(np.isinf(sdt))), nBoundaryChanges=n_boundary, nSamples=len(gt),
                sdtPerSwitch=sdt, ellPerSwitch=ell, nOverlap=nov)


def aggregate(per_subject):
    acc = np.array([p["acc"] for p in per_subject], float)
    L = np.array([p["L"] for p in per_subject], float)
    sdt = np.array([p["sdt"] for p in per_subject], float)
    A = float(np.nanmean(acc)) if np.any(np.isfinite(acc)) else np.nan
    Lm = float(np.nanmean(L)) if np.any(np.isfinite(L)) else np.nan
    S = float(np.nanmedian(sdt)) if np.any(~np.isnan(sdt)) else np.nan
    a, b = A / 100.0, Lm
    H = 0.0 if (a + b) == 0 else 2 * a * b / (a + b)
    return dict(Acc=A, L=Lm, SDT=S, H=H, nSaturated=int(np.sum(np.isinf(sdt))),
                nSwitches=int(sum(p["nSwitches"] for p in per_subject)),
                nUndetected=int(sum(p["nUndetected"] for p in per_subject)))


# ---------------------------------------------------------------------------
# numba-compiled core with identical semantics (verified against the pure port in e0/e1 tests)
# ---------------------------------------------------------------------------
try:
    import numba

    @numba.njit(cache=True)
    def _latency_core(decision, att_label, sw, fs, nSearch, nSustain, t_start, t_end, restrict):
        nSamp = decision.shape[0]
        nSw = sw.shape[0]
        sdt = np.empty(nSw)
        n_overlap = 0
        for k in range(nSw):
            i0 = sw[k]
            new_lab = att_label[i0]
            old_lab = att_label[i0 - 1]
            lo = max(0, i0)
            hi = min(nSamp - 1, i0 + nSearch)
            if restrict:
                lo = max(lo, t_start[i0])
                hi = min(hi, t_end[i0])
            n = hi - lo + 1
            if k < nSw - 1 and sw[k + 1] <= hi:
                n_overlap += 1
            prefix_old = np.zeros(n + 1, np.int64)
            for j in range(n):
                prefix_old[j + 1] = prefix_old[j] + (1 if decision[lo + j] == old_lab else 0)
            suf_new = np.zeros(n + 1, np.int64)
            for j in range(n - 1, -1, -1):
                suf_new[j] = suf_new[j + 1] + (1 if decision[lo + j] == new_lab else 0)
            score = prefix_old[:n] + suf_new[:n]
            suf_arg = np.empty(n, np.int64)
            suf_arg[n - 1] = n - 1
            for i in range(n - 2, -1, -1):
                suf_arg[i] = i if score[i] >= score[suf_arg[i + 1]] else suf_arg[i + 1]
            ext_hi = min(nSamp - 1, lo + n - 1 + nSustain - 1)
            m = ext_hi - lo + 1
            run_new = np.zeros(m + 1, np.int64)
            for i in range(m - 1, -1, -1):
                if decision[lo + i] == new_lab:
                    run_new[i] = run_new[i + 1] + 1
            tau = -1
            lower = 0
            while lower <= n - 1:
                cand = suf_arg[lower]
                if lo + cand + nSustain - 1 <= nSamp - 1 and run_new[cand] >= nSustain:
                    tau = cand
                    break
                lower = cand + 1
            if tau < 0:
                sdt[k] = np.inf
            else:
                sdt[k] = abs(lo + tau - i0) / fs
        return sdt, n_overlap
except Exception:  # pragma: no cover
    _latency_core = None


def fast_score_subject(pred, gt, trial, fs=128, searchWindow=100.0, tSustain=0.5, tau0=60.0):
    """Same outputs as score_subject() (acc, sdt, L, ...), using the compiled core."""
    pred = np.asarray(pred, float)
    gt = np.asarray(gt, float)
    trial = np.asarray(trial)
    acc = float(np.mean(pred == gt) * 100)
    is_change = np.r_[False, np.diff(gt) != 0]
    is_new_trial = np.r_[False, np.diff(trial) != 0]
    sw = np.flatnonzero(is_change & ~is_new_trial).astype(np.int64)
    edges = np.r_[0, np.flatnonzero(np.diff(trial) != 0) + 1, len(trial)]
    t_start = np.empty(len(trial), np.int64)
    t_end = np.empty(len(trial), np.int64)
    for b in range(len(edges) - 1):
        t_start[edges[b]:edges[b + 1]] = edges[b]
        t_end[edges[b]:edges[b + 1]] = edges[b + 1] - 1
    if len(sw) == 0:
        return dict(acc=acc, sdt=np.nan, L=np.nan, nSwitches=0, nUndetected=0, sdtPerSwitch=np.zeros(0),
                    ellPerSwitch=np.zeros(0), nOverlap=0)
    sdt, nov = _latency_core(pred, gt, sw, float(fs), _mround(searchWindow * fs), max(1, _mround(tSustain * fs)),
                             t_start, t_end, True)
    ell = np.exp(-sdt / tau0)
    return dict(acc=acc, sdt=float(np.median(sdt)), L=float(np.median(ell)), nSwitches=len(sw),
                nUndetected=int(np.isinf(sdt).sum()), sdtPerSwitch=sdt, ellPerSwitch=ell, nOverlap=nov)
