"""Submission: retrain one all-five vlaai_ws decoder exactly as eval_external.py --tag _bestP (runners/run_m1_seed.sh dec)
and SAVE its weights (eval_external.py only stored the evidence).

Check of the reproduction: the AASD evidence of the new network is compared with results/research/
aasd_c1_bestP_evidence_s<SEED>.pkl (training is bit-exact on this machine); the run fails if the max difference
exceeds 1e-2 or the mean 1e-4 (evidence is stored as float16). Output: models/all5_vlaai_ws_bestP_s<SEED>.pt (state_dict of dec.net).
usage: GLIMPSE_THR=norm python sub_train_decoder.py --seed S
"""
import argparse
import os
import pickle

import numpy as np
import torch

import decoders
import eval_external as E
from common_exp import EXP

PREP = "eaP_n5_t60"

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--seed", type=int, required=True)
    a = ap.parse_args()
    assert os.environ.get("GLIMPSE_THR") == "norm", "the decoder recipe uses GLIMPSE_THR=norm"
    sfx = "" if a.seed == 0 else f"_s{a.seed}"
    init = os.path.join(EXP, "models", f"pretrain_spk_vlaai_ws_s{a.seed}.pt")
    out = os.path.join(EXP, "models", f"all5_vlaai_ws_bestP_s{a.seed}.pt")
    decoders.apply_overrides([])
    E.CONF.update(targets=["env", "onset", "dom"], ref=f"vlaai_ws__{PREP}_aug_cluster_onset_dom_xFUG_ptSPK{sfx}",
                  prep=PREP, decoder="vlaai_ws")
    E.CONF["aug_set"] = []
    dec = E.train(a.seed, (), ["Fuglsang2020"], init)
    torch.save(dec.net.state_dict(), out)
    print("saved", out, flush=True)
    ref = pickle.load(open(os.path.join(EXP, "results", "research", f"aasd_c1_bestP_evidence_s{a.seed}.pkl"), "rb"))
    new = E.evidence(dec, "AASD")
    diff = np.concatenate([np.abs(new[k]["r0f"].astype(float) - ref[k]["r0f"].astype(float)).ravel() for k in ref])
    d, m = float(diff.max()), float(diff.mean())
    print(f"AASD evidence vs aasd_c1_bestP_evidence_s{a.seed}: max |r0f difference| {d:.2e}, mean {m:.2e} "
          f"(float16 storage: one rounding step ~2e-4)", flush=True)
    if d > 1e-2 or m > 1e-4:
        raise SystemExit("reproduction check FAILED: the saved network is not the evaluated one")
    print("reproduction check passed", flush=True)
