"""The two halves of the direct classifier's decision, per 0.25-s step: gA = g(EEG, stream 0, stream 1), gB = g(EEG, stream 1, stream 0), logit = gA - gB
(the same windows and causal read-out as logits()). The streams are standardised per window first, exactly as DirectNet.forward does.
usage: python dump_g.py MODEL.pt TRIAL_KEY [--blocks 3] [--window-s 10] [--backbone vlaai_ws] -> prints a summary, saves results/research/g_<key>.npz"""
import argparse
import os

import numpy as np
import torch

import direct_classifier as DC
from common_exp import EXP, load_trial
from decoders import D, _targets


@torch.no_grad()
def dump(net, x, S):
    T = len(x)
    xp = np.concatenate([np.zeros((DC.POS0, x.shape[1]), np.float32), x.astype(np.float32), np.zeros((DC.FUT + DC.HOP, x.shape[1]), np.float32)])
    Sp = np.concatenate([np.zeros((DC.POS0,) + S.shape[1:], np.float32), S, np.zeros((DC.FUT + DC.HOP,) + S.shape[1:], np.float32)])
    starts = np.arange(0, T, DC.HOP)
    gA, gB = [], []
    for i in range(0, len(starts), 256):
        a = starts[i:i + 256]
        E, Sw = (torch.from_numpy(np.stack([z[k:k + DC.W] for k in a])).to(DC.DEV) for z in (xp, Sp))
        Sw = (Sw - Sw.mean(1, keepdim=True)) / (Sw.std(1, keepdim=True) + 1e-6)
        gA.append(net.g(E, Sw[:, :, 0], Sw[:, :, 1]).cpu().numpy())
        gB.append(net.g(E, Sw[:, :, 1], Sw[:, :, 0]).cpu().numpy())
    return np.concatenate(gA), np.concatenate(gB), starts


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("model")
    ap.add_argument("key")
    ap.add_argument("--blocks", type=int, default=3)
    ap.add_argument("--window-s", type=float, default=10)
    ap.add_argument("--backbone", default="vlaai_ws")
    ap.add_argument("--prep", default="eaP_n5_t60")
    a = ap.parse_args()
    D.update(targets=["env", "onset", "dom"], model_blocks=a.blocks)
    DC.W = int(a.window_s * DC.FS)
    DC.POS0, DC.LAB = DC.W - DC.FUT - DC.HOP, DC.W - DC.FS
    net = DC.DirectNet(58, 3, a.backbone).to(DC.DEV)
    net.load_state_dict(torch.load(a.model, map_location=DC.DEV, weights_only=True))
    net.eval()
    tr = load_trial(a.prep, a.key)
    gA, gB, starts = dump(net, tr["eeg"], _targets(tr))
    att = tr["att"].astype(int)[np.maximum(starts - DC.HOP, 0)]          # attended column 1 s before the window end (as logits() / run_fold)
    lg = gA - gB
    print(f"{a.key}: {len(lg)} steps; gA mean {gA.mean():+.3f} sd {gA.std():.3f} | gB mean {gB.mean():+.3f} sd {gB.std():.3f} | corr(gA, gB) {np.corrcoef(gA, gB)[0, 1]:+.3f}")
    print(f"  logit = gA - gB: mean {lg.mean():+.3f} sd {lg.std():.3f}; steps with the right sign {np.mean((lg > 0) == (att == 0)):.3f}")
    for i in range(0, len(lg), max(1, len(lg) // 8)):
        print(f"  t {starts[i] / DC.FS:6.2f} s  gA {gA[i]:+.3f}  gB {gB[i]:+.3f}  logit {lg[i]:+.3f}  attended column {att[i]}")
    np.savez(os.path.join(EXP, "results", "research", f"g_{a.key}.npz"), gA=gA, gB=gB, logit=lg, t=starts / DC.FS, att=att)
