"""BOCPD follow-ups on saved evidence. Wilson-style discrete hazard hierarchy;
Student-t predictive likelihood with approximate robust Gaussian updates.
Noise is injected into evidence, not EEG. Outputs per dataset and replicate.
"""
import argparse
import math
import multiprocessing as mp
import os
import numpy as np
import pandas as pd
from numba import njit
import hmm_bocpd as B


@njit(cache=True)
def filt(x, sig, tau, learned, robust):
    # Discrete hazard states approximate a Wilson hierarchy. Hazard redraw is
    # uniform at higher-order change points, with probability 1/1200 per step.
    hs = np.array([1/20, 1/40, 1/80, 1/160, 1/320, 1/500]) if learned else np.array([1/80])
    K, R = len(hs), 480
    w = np.zeros((K, R)); w[:, 0] = 1.0 / K
    m = np.zeros((K, R)); v = np.full((K, R), tau*tau)
    out = np.empty(len(x)); sig2 = sig*sig
    for t in range(len(x)):
        if t:
            nw = np.zeros((K, R)); nm = np.zeros((K, R)); nv = np.full((K, R), tau*tau)
            # For each run length, hazard may persist or be redrawn.
            for k in range(K):
                for r in range(R):
                    for j in range(K):
                        p = ((1.0 - 1/1200) if j == k else 0.0) + (1/1200)/K if learned else 1.0
                        z = w[k,r]*p
                        nw[j,0] += z*hs[j]
                        # cap last bin; merging moments preserves first two moments
                        q = min(r+1,R-1); z *= 1-hs[j]
                        if z > 1e-280:
                            old = nw[j,q]; new = old+z
                            fraction = z/new
                            delta = m[k,r]-nm[j,q]
                            nm[j,q] += fraction*delta
                            nv[j,q] = (1-fraction)*nv[j,q]+fraction*v[k,r]+fraction*(1-fraction)*delta*delta
                            nw[j,q] = new
            w,m,v = nw,nm,nv
        total = 0.0
        for k in range(K):
            for r in range(R):
                if w[k,r] == 0: continue
                var = sig2+v[k,r]; resid = x[t]-m[k,r]
                if robust:
                    # df=4, equal predictive variance; Student-t density.
                    scale2 = var/2.0
                    likelihood = math.exp(math.lgamma(2.5)-math.lgamma(2.0)) / math.sqrt(4*math.pi*scale2) * (1+resid*resid/(4*scale2))**(-2.5)
                    weight = min(1.0, 5.0/(4.0+resid*resid/scale2))
                else:
                    likelihood = math.exp(-0.5*resid*resid/var)/math.sqrt(2*math.pi*var)
                    weight = 1.0
                w[k,r] *= likelihood; total += w[k,r]
                gain = v[k,r]*weight/(sig2+v[k,r]*weight)
                m[k,r] += gain*resid; v[k,r] *= 1-gain
        if total <= 1e-300: raise ValueError('likelihood underflow')
        p1 = 0.0
        for k in range(K):
            for r in range(R):
                w[k,r] /= total
                if w[k,r] > 0:
                    p1 += w[k,r]*0.5*(1+math.erf(-m[k,r]/math.sqrt(2*max(v[k,r], tau*tau*1e-12))))
        out[t] = p1
    return out


TASK = None
def run_task(args):
    return TASK(args)


def main(mode):
    import fuse_external as FX, fuse_general as FG, eval_external as E, score as S, e1_switch
    from common import DS_KEYS
    from common_exp import EXP
    from fuse_evidence import LA
    dec = ['vlaai_ws__eaP_n5_t60_aug_cluster_onset_dom_xFUG_ptSPK'+s for s in ('','_s1','_s2','_s3')]
    clf = ['direct_clf__eaP_n5_t60_w10b3_ptSPK'+s+'_aug-sw2' for s in ('','_s1','_s2','_s3')]
    reps = {'all4':[0,1,2,3], 's01':[0,1], 's23':[2,3]}
    cur = {}
    def integ(d, p):
        d = np.asarray(d, dtype=float)
        # Same RNG seed per task gives paired noise for each algorithm.
        rng = cur['rng']
        if cur['noise'] == 'gauss': d = d + rng.normal(0, 0.5*p['sd'], len(d))
        if cur['noise'] == 'impulse': d = d + (rng.random(len(d)) < 0.05)*rng.normal(0, 4*p['sd'], len(d))
        if cur['method'] == 'hmm': return e1_switch.integ_hmm(d, dict(p_stay=0.998, mu=p['mu'], sd=p['sd']))
        mu, sd = abs(p['mu']), p['sd']
        sig = math.sqrt(max(sd*sd-mu*mu, .05*sd*sd))
        if cur['method'] == 'bma': return (B.bocpd_filter(d, sig, .5*mu, B.LAMS) > .5).astype(int)
        return (filt(d, sig, .5*mu, cur['method']=='learned', cur['method']=='robust') > .5).astype(int)
    S.integ_hmm = integ; E.integ_hmm = integ
    data = {}
    for rep, ids in reps.items():
        print('building evidence',rep,flush=True)
        z, meta = FG.build([dec[i] for i in ids], [clf[i] for i in ids])
        er, em = FX.build_external([[dec[i],str(i)] for i in ids], [[clf[i],'_w10b3sw2P',str(i)] for i in ids], [.5], ['AASD','Carta2026'], '_bestP')
        data[rep] = z, meta, er, em[.5]
    def task(a):
        rep, ds, method, noise = a
        cur.update(method=method, noise=noise, rng=np.random.default_rng(7182))
        z, meta, er, em = data[rep]
        if ds in DS_KEYS:
            zd, zc = z[ds]
            ev = {d:{k:dict(r0=.5*zd[d][k]+.5*zc[d][k],r1=np.zeros(len(zd[d][k])),att=meta[d][k][0],t_end=meta[d][k][1],pre_switched=True) for k in zd[d]} for d in DS_KEYS}
            res = S.score_dataset(ds, ev, LA, p_stay=.998)
        else: res = E.score(er[ds][.5], *em, .998, LA)
        return dict(rep=rep,ds=ds,method=method,noise=noise,H=res['H'],Acc=res['Acc'],SDT=res['SDT'])
    methods = ['hmm','bma',mode]
    noises = ['clean'] if mode=='learned' else ['clean','gauss','impulse']
    tasks = [(r,d,m,n) for r in reps for n in noises for m in methods for d in ['AASD','Carta2026']+list(DS_KEYS)]
    path = os.path.join(EXP,'results','research','bocpd_'+mode+'_followup_v2.csv')
    if os.path.exists(path): raise FileExistsError(path)
    global TASK
    TASK = task
    with mp.get_context('fork').Pool(int(os.environ.get('SCORE_JOBS',3))) as pool:
        for i,row in enumerate(pool.imap_unordered(run_task,tasks)):
            pd.DataFrame([row]).to_csv(path,mode='a',header=not os.path.exists(path),index=False)
            if i%10==0: print(f'{i+1}/{len(tasks)} {row}',flush=True)
    print('finished',path,flush=True)

if __name__ == '__main__':
    ap=argparse.ArgumentParser(); ap.add_argument('mode',choices=['learned','robust']); main(ap.parse_args().mode)
