"""Re-run the LODO direct classifiers on OTHER synthetic-switch schedules (weights saved by SAVE_FOLD_WEIGHTS=1 direct_classifier.py).

The classifier takes the switch at its INPUT (stimulus columns swapped), so a different schedule needs new inference, not a
re-labelling. For each held-out dataset the fold net (models/fold_<exp>__<held>.pt) is run causally on the swapped input exactly as
direct_classifier.run_fold does, with the schedule rng = default_rng(SEED + OFFSET + dataset index) (OFFSET 0 = the usual schedule).
Writes folds/<exp>__sched<OFFSET>/<DS>.pkl (same layout as a fold file; `controls` omitted), loadable with score.load_folds.
OFFSET 0 is not written; it is re-computed and compared with folds/<exp>/<DS>.pkl as a check of the pipeline.
usage: python clf_reschedule.py --exp direct_clf__eaP_n5_t60_w10b3_ptSPK_aug-sw2_wts --prep eaP_n5_t60 --window-s 10
           --set model_blocks=3 --offsets 0 1000 2000 3000 4000"""
import argparse
import os
import pickle

import numpy as np
import torch

import decoders
import direct_classifier as DC
from common import DS_KEYS, SEED
from common_exp import CFG, EXP, FS, fold_file, load_trial, rows_of
from decoders import D, _targets
from e1_switch import draw_switch_times

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--exp", required=True)
    ap.add_argument("--prep", default="eaP_n5_t60")
    ap.add_argument("--window-s", type=float, default=10.0)
    ap.add_argument("--set", nargs="*", default=[])
    ap.add_argument("--aug-variant", default="cluster")
    ap.add_argument("--offsets", nargs="+", type=int, required=True)
    ap.add_argument("--datasets", nargs="+", default=DS_KEYS, help="held-out datasets to process (default all five)")
    a = ap.parse_args()
    DC.W = int(a.window_s * FS)
    DC.POS0, DC.LAB = DC.W - DC.FUT - DC.HOP, DC.W - FS
    D["targets"] = ["env", "onset", "dom"]
    D["augment"] = {**CFG["dnn_augment"], **CFG["aug_variants"][a.aug_variant]}
    decoders.apply_overrides(a.set, [])
    torch.set_num_threads(4)
    W, HOP, FUT = DC.W, DC.HOP, DC.FUT
    for held in a.datasets:
        outs = {k: os.path.join(EXP, "folds", f"{a.exp}__sched{k}", f"{held}.pkl") for k in a.offsets if k != 0}
        if all(os.path.exists(p) for p in outs.values()) and 0 not in a.offsets:
            print(f"{held}: cached", flush=True)
            continue
        stored = pickle.load(open(fold_file(a.exp, held), "rb"))
        rows = list(rows_of(held).iterrows())
        Fs = _targets(load_trial(a.prep, rows[0][1]["key"])).shape[-1]
        net = DC.DirectNet(58, Fs, "vlaai_ws").to(DC.DEV)
        net.load_state_dict(torch.load(os.path.join(EXP, "models", f"fold_{a.exp}__{held}.pt"), map_location=DC.DEV))
        net.eval()
        ev = {k: {} for k in a.offsets}
        rngs = {k: np.random.default_rng(SEED + k + DS_KEYS.index(held)) for k in a.offsets}
        for _, r in rows:
            tr = load_trial(a.prep, r["key"])
            S, x, att, T128 = _targets(tr), tr["eeg"], tr["att"].astype(int), int(r["n"])
            for k in a.offsets:
                times = draw_switch_times(rngs[k], T128 / 128)
                rngs[k].integers(0, 2)                                       # the scorer's start guess (same stream)
                st128, cur, prev = np.zeros(T128, bool), False, 0
                for tt in times:
                    s0 = min(T128 - 1, int(round(tt * 128)))
                    st128[prev:s0] = cur
                    cur, prev = not cur, s0
                st128[prev:] = cur
                st = st128[np.minimum(T128 - 1, np.round((np.arange(len(x)) / FS + tr["t0"]) * 128).astype(int))]
                lg, starts = DC.logits(net, x, np.where(st[:, None, None], S[:, ::-1], S))
                truth = (att ^ st)[np.maximum(starts - HOP, 0)]
                n10 = len(lg) // 40
                ev[k][r["key"]] = dict(r0=lg / 2, r1=-lg / 2, att=truth.astype(np.int8), t_end=(starts / FS + tr["t0"]).astype(np.float32),
                                       r0_10=lg[:n10 * 40].reshape(n10, 40).mean(1) / 2, r1_10=-lg[:n10 * 40].reshape(n10, 40).mean(1) / 2,
                                       att10=(truth[:n10 * 40].reshape(n10, 40).mean(1) > 0.5).astype(np.int8), pre_switched=True)
        if 0 in ev:
            ref = stored["evidence"]["causal"]
            d = max(float(np.abs(ev[0][key]["r0"] - ref[key]["r0"]).max()) for key in ref)
            n_att = sum(int((ev[0][key]["att"] != ref[key]["att"]).sum()) for key in ref)
            print(f"{held}: offset 0 vs stored fold: max |logit/2 difference| {d:.2e}, truth labels differing: {n_att}", flush=True)
        for k, path in outs.items():
            os.makedirs(os.path.dirname(path), exist_ok=True)
            info = dict(stored["info"], schedule_offset=k, controls={})
            with open(path, "wb") as fh:
                pickle.dump(dict(evidence={"causal": ev[k]}, info=info), fh)
            print(f"{held}: wrote {path}", flush=True)
        del net
        torch.cuda.empty_cache()
