"""Structural raw-input perturbation probe; pretrained first stage is a surrogate.

Feature-vector assembly repeats aggregate evidence as a timing proxy, not the
16 actual trained model outputs. This supplements, never certifies, the scored
pipeline. Negative control shifts evidence one full second into the future.
"""
import os
import numpy as np
import pandas as pd
import torch
import leakage_test as L
import antisym_transformer_experiment as T
from rate_aux_baseline_ensemble import model_for
from common import DS_KEYS,load_pp,load_env
from common_exp import EXP,CFG,FS,rows_of
from e1_switch import expand,hmm_filter
from run_experiment import init_net

def main():
 torch.set_num_threads(2);torch.manual_seed(0);rng=np.random.default_rng(3)
 L.decoders.D['targets']=['env','onset','dom'];L.decoders.D['model_blocks']=3
 dec=L.decoders.make('vlaai_ws',58,lambda *a:None)
 # decoder is 4 blocks; D model_blocks affects its construction
 L.decoders.D['model_blocks']=4
 dec=L.decoders.make('vlaai_ws',58,lambda *a:None)
 init_net(dec,os.path.join(EXP,'models','pretrain_spk_vlaai_ws_s0.pt'),lambda *a:None);dec.net.eval()
 L.decoders.D['model_blocks']=3;L.DC.W=10*FS;L.DC.POS0=L.DC.W-L.DC.FUT-L.DC.HOP
 clf=L.DC.DirectNet(58,3).to(L.DC.DEV)
 clf.load_state_dict(torch.load(os.path.join(EXP,'models','pretrain_spk_direct_clf_w10_b3_s0.pt'),map_location=L.DC.DEV,weights_only=True));clf.eval()
 models=[model_for('ALL',i,torch.device('cpu')) for i in range(4)]
 def calc(x,e,raw,t0,n):
  got=L.evidences(x,e,raw,t0,dec,{10:clf})
  d,te,_=got['decoder, DEFAULT stamping (dec.lookahead_s = 0.5)'];c,tc,la=got['direct classifier, 10-s window']
  off=3;nn=min(len(d),len(c)-off);assert np.allclose(te[:nn],tc[off:off+nn]+.25,atol=1e-3)
  z=np.column_stack([c[off:off+nn]]*4+[d[:nn]]*12).astype('f')
  def tf(v):return np.mean([T.predict(m,v,s,torch.device('cpu')) for m,s in models],axis=0)
  f=.75*(d[:nn]+c[off:off+nn])+.25*tf(z)
  future=np.r_[z[4:],np.repeat(z[-1:],4,axis=0)];bad=.75*(d[:nn]+c[off:off+nn])+.25*tf(future)
  out={}
  for name,v in [('surrogate_ensemble',f),('negative_future_1s',bad)]:
   p=hmm_filter(-.5*(v-.5)**2,-.5*(v+.5)**2,.998)
   out[name]=np.stack([expand(v,tc[off:off+nn],la,n,0),expand(p,tc[off:off+nn],la,n,0)])
  return out
 rows=[]
 for ds in DS_KEYS:
  r=rows_of(ds).iloc[0];v=load_pp(r,'sup',CFG['montage'],do_car=True,do_runz=False,do_trim=True)
  n=min(len(v['eeg']),40*FS);x=L.zscore_trial(v['eeg'])[:n];e=L.zscore_trial(v['env'])[:n]
  raw=load_env(r['key']).astype(float)[:4*(n+2*FS)];t0=float(v['t0_s']);pres=np.flatnonzero(v['present']);n128=len(raw)
  before=calc(x,e,raw,t0,n128)
  for pos in [n//2+k for k in range(8)]:
   for what in ('EEG','stimulus','EEG+stimulus'):
    x2=x.copy();e2=e.copy();raw2=raw.copy()
    if 'EEG' in what:x2[pos:,pres]=3*rng.standard_normal((n-pos,len(pres)))
    if 'stimulus' in what:
     e2[pos:]=3*rng.standard_normal(e2[pos:].shape)
     raw2[4*(pos+FS):]=abs(rng.standard_normal(raw2[4*(pos+FS):].shape))*3*raw.mean()
    aft=calc(x2,e2,raw2,t0,n128);tau=pos/FS+t0
    for name in before:
     ix=np.flatnonzero((before[name]!=aft[name]).any(axis=0))
     rows.append(dict(dataset=ds,mode=what,pipeline=name,lookahead=tau-ix[0]/128 if len(ix) else np.nan,changed=len(ix)))
  print(ds,'done',flush=True)
 df=pd.DataFrame(rows);path=os.path.join(EXP,'results','research','audit_transformer_leakage_surrogate.csv');df.to_csv(path,index=False)
 print(df.groupby(['pipeline','mode']).agg(tests=('changed','size'),changed=('changed',lambda v:(v>0).sum()),max_lookahead=('lookahead','max')).to_string(),flush=True)
 real=df[df.pipeline=='surrogate_ensemble'];neg=df[(df.pipeline=='negative_future_1s') & (df['mode']!='stimulus')]
 assert real.changed.gt(0).all() and real.lookahead.le(1).all() and neg.lookahead.gt(1).all()
 print('PASS structural proxy only; actual 4+4 EEG-to-output inference not verified',flush=True)
if __name__=='__main__':main()
