"""Dominance / relative-onset targets for SparrKULee PRETRAINING (single talker).

There is no second talker, so the "other stream" is the mismatched negative already used by convert_sparrkulee.py:
the run's own envelope circularly shifted by half its length (never presented to the listener). dom / orel / odiff are
then computed exactly as decoder_lodo/build_glimpse.py ('onorm', its features()), from the authors' unfiltered
envelope (64 Hz, gammatone |.|^0.6) upsampled to 128 Hz. Purpose: pretrain ALL output columns of a multi-target
decoder (env, onset, dom, orel) instead of leaving the dom / orel columns to a fresh initialisation at fine-tuning.
Output cache/glimpseonorm/<key>.npz (dom, orel, odiff at 32 Hz, aligned with cache/mat_reac).
usage: python build_glimpse_spk.py onorm"""
import os
import sys

import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy.signal import resample_poly

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "..", "decoder_lodo"))
import build_glimpse as BG  # noqa: E402  (reads the same command-line argument)

OUT = os.path.join(HERE, "cache", f"glimpse{BG.ARG}")


def build(key, stim):
    p = os.path.join(OUT, key + ".npz")
    if os.path.exists(p):
        return 0
    T = len(np.load(os.path.join(HERE, "cache", "mat_reac", key + ".npz"))["env"])
    n = T + 64                                               # 32-Hz length before the 1-s edge trim (converter)
    e64 = np.load(os.path.join(HERE, "raw", "preprocessed_stimuli", f"{stim}_-_envelope.npy")).astype(np.float64).reshape(-1)
    e = resample_poly(e64[:2 * n], 2, 1)                     # 128 Hz, length 4 n
    F = BG.features(np.stack([e, np.roll(e, 4 * (n // 2))], 1))   # same half-length shift as the converter
    F = {k: F[k][::4][32:32 + T].astype(np.float32) for k in ("dom", "orel", "odiff")}
    assert len(F["dom"]) == T, (key, len(F["dom"]), T)
    np.savez(p, **F)
    return 1


if __name__ == "__main__":
    os.makedirs(OUT, exist_ok=True)
    I = pd.read_csv(os.path.join(HERE, "cache", "index_mat_reac.csv"))
    I = I[I.n > 0]
    n = sum(Parallel(n_jobs=3)(delayed(build)(r.key, r.stim) for r in I.itertuples()))
    print(f"SparrKULee glimpse{BG.ARG}: built {n} of {len(I)}")
