"""Re-infer pair-excluded or outer-OOF DirectNet on varied TRAIN schedules.

Never change the official held-out evaluation schedule. Profiles and trial
states are deterministic across all four seed models. Every output records
switch times and initial stream exchange for exact decoder alignment.
"""
import argparse
import os
import zlib

import numpy as np
import torch

import direct_classifier as DC
from common import DS_KEYS, SEED
from common_exp import EXP, FS, load_trial, rows_of, save_pickle
from decoders import D, _targets
from e1_switch import draw_switch_times
from nested_stack_base import ROOT as PAIR_ROOT, pair_name
from eval_stem_external import REF

ROOT = os.path.join(EXP,'folds','nested_schedule_aug')
PROFILES = {'fast':(12.,3.), 'medium':(30.,8.), 'slow':(60.,15.)}


def schedule(ds, key, duration_samples, profile):
    mean, minimum = PROFILES[profile]
    # No reliance on Python's salted hash; seed independent of model seed.
    token=f'{ds}|{key}|{profile}'.encode()
    rng=np.random.default_rng(SEED+zlib.crc32(token))
    initial=bool(rng.integers(0,2))
    times=draw_switch_times(rng,duration_samples/128,mean_int=mean,min_seg=minimum)
    return initial,times


def switch_mask(n, initial, times):
    st=np.full(n,initial,dtype=bool)
    for tt in times:
        st[min(n-1,int(round(float(tt)*128))):] ^= True
    return st


def main():
    p=argparse.ArgumentParser()
    p.add_argument('--pair',nargs=2,choices=DS_KEYS)
    p.add_argument('--oof',choices=DS_KEYS)
    p.add_argument('--seed',type=int,choices=range(4),required=True)
    a=p.parse_args()
    if bool(a.pair)==bool(a.oof) or (a.pair and a.pair[0]==a.pair[1]):
        p.error('choose either two distinct --pair datasets or one --oof dataset')
    torch.set_num_threads(2)
    DC.W=10*FS; DC.POS0,DC.LAB=DC.W-DC.FUT-DC.HOP,DC.W-FS
    D.update(targets=['env','onset','dom'],model_blocks=3)
    if a.pair:
        excluded=sorted(a.pair); group=pair_name(*excluded)
        modelpath=os.path.join(PAIR_ROOT,group,f'seed{a.seed}','model.pt')
    else:
        excluded=[a.oof]; group='oof_'+a.oof
        modelpath=os.path.join(EXP,'models',f'fold_{REF[a.seed]}_wts__{a.oof}.pt')
    if not os.path.isfile(modelpath): raise FileNotFoundError(modelpath)
    net=DC.DirectNet(58,3,'vlaai_ws').to(DC.DEV)
    net.load_state_dict(torch.load(modelpath,map_location=DC.DEV,weights_only=True));net.eval()
    for ds in excluded:
        outputs={pr:{} for pr in PROFILES}
        counts={pr:[] for pr in PROFILES}
        for _,r in rows_of(ds).iterrows():
            tr=load_trial('eaP_n5_t60',r['key'])
            stim,x,att,n=_targets(tr),tr['eeg'],tr['att'].astype(int),int(r['n'])
            idx=np.minimum(n-1,np.round((np.arange(len(x))/FS+tr['t0'])*128).astype(int))
            for pr in PROFILES:
                initial,times=schedule(ds,r['key'],n,pr)
                state=switch_mask(n,initial,times); st=state[idx]
                lg,starts=DC.logits(net,x,np.where(st[:,None,None],stim[:,::-1],stim))
                truth=(att^st)[np.maximum(starts-DC.HOP,0)]
                outputs[pr][r['key']]=dict(r0=lg/2,r1=-lg/2,att=truth.astype(np.int8),
                    t_end=(starts/FS+tr['t0']).astype(np.float32),pre_switched=True,
                    switch_times=times,initial_swap=initial)
                counts[pr].append(len(times))
        for pr,ev in outputs.items():
            path=os.path.join(ROOT,group,f'seed{a.seed}',pr,ds+'.pkl')
            info=dict(excluded_datasets=excluded,scored_dataset=ds,seed=a.seed,profile=pr,
                switch_counts=dict(trials=len(counts[pr]),no_switch=sum(n==0 for n in counts[pr]),
                                   total=sum(counts[pr])),source_model=modelpath,
                lookahead_s=(DC.FUT+DC.HOP)/FS)
            save_pickle(dict(info=info,evidence={'causal':ev}),path)
            print('wrote',path,info['switch_counts'],flush=True)


if __name__=='__main__':main()
