"""F11: frozen REVE-base embedding of every pre-N2 window -> cache/F11.npy (n, 512) float16 + F11_names.npy.

The E4 filtered window (low-pass 45 Hz, 128 Hz) is resampled to 200 Hz (1000 samples), z-scored per channel and clamped to +-15 as in the
organisers' reve_probe.py; REVE (braindecode, `brain-bzh/reve-base`, pre-staged on the Codabench worker) is run with the Muse electrode
names (TP9, AF7, AF8, TP10 are in its position bank). Features (B, 4, 5, 512) are averaged over channels and the 5 time patches. Window by
window, no context: causal and streamable.  Declare the corpus in the submission (Rule 04): REVE is pre-trained on public EEG.
usage: python build_reve.py [batch, default 256]
"""
import os
import sys
import time

import numpy as np
import torch
import torch.nn.functional as F
from braindecode.models import REVE

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
E4C = os.path.join(ROOT, "experiments/e4_start/cache")
BS = int(sys.argv[1]) if len(sys.argv) > 1 else 256
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("device", dev, flush=True)
m = REVE.from_pretrained("brain-bzh/reve-base", n_outputs=1, n_chans=4, n_times=1000, sfreq=200, chs_info=None).to(dev)
m.default_pos = m.get_positions(["TP9", "AF7", "AF8", "TP10"]); m.eval().requires_grad_(False)
raw = np.load(f"{E4C}/mask_raw_f16.npy", mmap_mode="r")
out = np.empty((len(raw), 512), np.float16)
t0 = time.time()
with torch.inference_mode():
    for i in range(0, len(raw), BS):
        x = torch.from_numpy(np.asarray(raw[i:i + BS], dtype=np.float32)).to(dev)
        x = F.interpolate(x, size=1000, mode="linear", align_corners=False)
        x = ((x - x.mean(-1, keepdim=True)) / x.std(-1, keepdim=True, unbiased=False).clamp_min(1e-6)).clamp(-15, 15)
        with torch.autocast(dev.type, dtype=torch.float16, enabled=dev.type == "cuda"):
            f = m(x, return_features=True)["features"]
        out[i:i + BS] = f.float().mean((1, 2)).cpu().numpy().astype(np.float16)
        if (i // BS) % 40 == 0:
            print(f"{i}/{len(raw)} windows, {time.time() - t0:.0f} s", flush=True)
np.save(os.path.join(HERE, "cache", "F11.npy"), out)
np.save(os.path.join(HERE, "cache", "F11_names.npy"), np.array([f"reve_{k:03d}" for k in range(512)]))
print("done", out.shape, f"{time.time() - t0:.0f} s, finite {np.isfinite(out.astype(np.float32)).all()}", flush=True)
