"""Shared helpers: paths, prepared data, sliding-window evidence, LODO folds."""
from __future__ import annotations

import os
import pickle
import sys

import numpy as np
import yaml

EXP = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(EXP, "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "reports", "eda_full", "scripts"))
sys.path.insert(0, os.path.join(ROOT, "baselines", "python", "SuperHugeAAD"))
from common import DS_KEYS, trial_index  # noqa: E402

CFG = yaml.safe_load(open(os.path.join(EXP, "config.yaml")))
FS = CFG["fs"]
LAB = {"AVGC": "KUL-AV-GC", "DTU": "DTU", "KUL": "KUL2016", "UHD": "KUL-UHD", "USTC": "USTC"}


def cache_path(prep, key):
    return os.path.join(EXP, "cache", prep, f"{key}.npz")


GLIMPSE_THR = os.environ.get("GLIMPSE_THR", "10")      # build_glimpse.py threshold (dB) of the glimpse targets


def load_trial(prep, key):
    z = np.load(cache_path(prep, key))
    tr = dict(eeg=z["eeg"], env=z["env"], att=z["att"], t0=float(z["t0"]), key=key)
    g = os.path.join(EXP, "cache", f"glimpse{GLIMPSE_THR}", f"{key}.npz")
    if os.path.exists(g):                                  # causal glimpsed / masked envelope targets (T, 2) each
        zg = np.load(g)
        tr.update({k: zg[k] for k in zg.files if k != "m"})   # glim, mask (+ dom, orel, odiff)
    return tr


def rows_of(ds):
    ti = trial_index()
    return ti[ti.ds == ds].reset_index(drop=True)


def sliding_corr(A, B, W, H, per_feature=False):
    """Mean over features of the windowed Pearson correlation between A (T,F) and B (T,F).
    Windows of W samples every H samples, starting at 0. Returns (r (n,), starts (n,)); per_feature -> r (n, F)."""
    A = np.asarray(A, float)
    B = np.asarray(B, float)
    if A.ndim == 1:
        A = A[:, None]
    if B.ndim == 1:
        B = B[:, None]
    n = min(len(A), len(B))
    A, B = A[:n], B[:n]
    starts = np.arange(0, n - W + 1, H)
    if len(starts) == 0:
        return np.zeros(0), starts

    def cs(x):
        return np.concatenate([np.zeros((1,) + x.shape[1:]), np.cumsum(x, 0)], 0)

    def win(c):
        return c[starts + W] - c[starts]

    sa, sb = win(cs(A)), win(cs(B))
    saa, sbb, sab = win(cs(A * A)), win(cs(B * B)), win(cs(A * B))
    cov = sab - sa * sb / W
    va = np.maximum(saa - sa ** 2 / W, 1e-12)
    vb = np.maximum(sbb - sb ** 2 / W, 1e-12)
    r = cov / np.sqrt(va * vb)
    return (r if per_feature else r.mean(1)), starts


def evidence_from_features(A, B0, B1, att, t0):
    """1-s windows at 0.25-s hop (for the integrator) and 10-s non-overlapping windows (plain accuracy)."""
    W, Hh = int(CFG["evidence"]["win_s"] * FS), int(CFG["evidence"]["hop_s"] * FS)
    r0f, st = sliding_corr(A, B0, W, Hh, per_feature=True)
    r1f, _ = sliding_corr(A, B1, W, Hh, per_feature=True)
    r0, r1 = r0f.mean(1), r1f.mean(1)
    c = np.concatenate([[0], np.cumsum(att[: len(A)])])
    att_w = ((c[st + W] - c[st]) / W > 0.5).astype(np.int8)
    W10 = int(CFG["evidence"]["win10_s"] * FS)
    q0, s10 = sliding_corr(A, B0, W10, W10)
    q1, _ = sliding_corr(A, B1, W10, W10)
    att10 = ((c[s10 + W10] - c[s10]) / W10 > 0.5).astype(np.int8) if len(s10) else np.zeros(0, np.int8)
    return dict(r0=r0.astype(np.float32), r1=r1.astype(np.float32), att=att_w,
                t_end=((st + W) / FS + t0).astype(np.float32),
                r0_10=q0.astype(np.float32), r1_10=q1.astype(np.float32), att10=att10,
                # per-target evidence (decision_targets.py); only for multi-target decoders
                **(dict(r0f=r0f.astype(np.float16), r1f=r1f.astype(np.float16)) if r0f.shape[1] > 1 else {}))


def fold_file(exp, ds):
    return os.path.join(EXP, "folds", exp, f"{ds}.pkl")


def save_pickle(obj, path):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "wb") as fh:
        pickle.dump(obj, fh)
    os.replace(tmp, path)
