"""HMM whose stay probability is gated by a transition detector (A4; idea of SGAD, arXiv 2608.01618).

p_stay(t) = (1 - q_t) * p_hi + q_t * p_lo, q_t = P(a switch happened in the last 5 s) from the auxiliary head of the direct classifier
(causal: q_t uses the same window as the logit at t). With q = 0 it is exactly e1_switch.integ_hmm."""
import numpy as np
from common import FS as FS128, SEED
from e1_switch import expand
from scorer import aggregate, fast_score_subject


def integ_hmm_gated(d, q, p_hi, p_lo, mu, sd):
    ll0 = -0.5 * ((d - mu) / sd) ** 2
    ll1 = -0.5 * ((d + mu) / sd) ** 2
    lp0 = lp1 = np.log(0.5)
    out = np.empty(len(d), int)
    for t in range(len(d)):
        if t > 0:
            p = (1.0 - q[t]) * p_hi + q[t] * p_lo
            a = np.logaddexp(lp0 + np.log(p), lp1 + np.log(1 - p))
            b = np.logaddexp(lp1 + np.log(p), lp0 + np.log(1 - p))
            lp0, lp1 = a, b
        lp0 += ll0[t]
        lp1 += ll1[t]
        nrm = np.logaddexp(lp0, lp1)
        lp0 -= nrm
        lp1 -= nrm
        out[t] = lp1 > lp0
    return out


def score_gated(ev, mu, sd, p_hi, p_lo, lookahead=0.75):
    """Same bookkeeping as eval_external.score, with the gated HMM. ev[trial]: r0, r1, sw (P(switch)), t_end, n128, att128, subject."""
    rng = np.random.default_rng(SEED)
    per = {}
    for k in sorted(ev):
        e = ev[k]
        d = (e["r0"] - e["r1"]).astype(float)
        dec = integ_hmm_gated(d, e["sw"].astype(float), p_hi, p_lo, mu, sd)
        labs = expand(dec, e["t_end"].astype(float), lookahead, e["n128"], int(rng.integers(0, 2)))
        per.setdefault(e["subject"], []).append((labs, e["att128"].astype(float)))
    res = []
    for s, 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"])


def score_dataset_gated(ds, ev, lookahead, p_hi, p_lo, use_gate=True):
    """score.score_dataset (synthetic-switch LODO, evidence flagged pre_switched) with the gated HMM; ev[ds][trial]["sw"] = P(switch).
    use_gate=False -> q = 0, which reproduces score.score_dataset with p_stay = p_hi."""
    import os
    import score as S
    from common import DS_KEYS
    from common_exp import rows_of
    from e1_switch import synth_trial
    train = [d for d in DS_KEYS if d != ds]
    A = np.concatenate([(e["r0"] - e["r1"]) * np.where(e["att"] == 0, 1.0, -1.0) for d in train for e in ev[d].values()])
    mu, sd = float(A.mean()), float(A.std())
    rng = np.random.default_rng(SEED + S.SCHED + DS_KEYS.index(ds))
    per = {}
    for _, r in rows_of(ds).iterrows():
        T = int(r["n"])
        e = ev[ds][r["key"]]
        att = np.load(os.path.join(S.EDA_CACHE, "cnd", f"{r['key']}.npz"))["att_col"][:T].astype(int)
        d = (e["r0"] - e["r1"]).astype(float)
        t_end = e["t_end"].astype(float)
        st, _, _ = synth_trial(r["key"], T, d, t_end, rng)
        guess = int(rng.integers(0, 2))
        q = e["sw"].astype(float) if use_gate else np.zeros(len(d))
        dec = integ_hmm_gated(d, q, p_hi, p_lo, mu, sd)
        per.setdefault(r["subj_uid"], []).append((expand(dec, t_end, lookahead, T, guess), np.where(st, 1 - att, att)))
    res = []
    for lst in per.values():
        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"])
