"""R2-3 PAD Step 0: frozen dominance-channel presentation diagnostic."""
from __future__ import annotations

import json
import os
import time

os.environ.setdefault("GLIMPSE_THR", "onorm")

import numpy as np
import torch
from scipy.io import loadmat

import eval_external as E
from common import DS_KEYS
from common_exp import EXP, ROOT, load_trial, rows_of
from decoders import _targets
from lagbank_sel import configure, external_targets, load_nets
from mm_diag import fold_nets, mean_logits

RUN_ID = "r2_pad_diag_20261107"
RUN_DIR = os.path.join(EXP, "experiments", "multi_agent_opt", "runs", RUN_ID)
OUT = os.path.join(EXP, "results", "research", "pad_diag.json")


def kul_conditions() -> dict[tuple[int, int], str]:
    out = {}
    base = os.path.join(ROOT, "data", "cnd", "KUL2016", "dataCND")
    for subject in range(1, 17):
        stim = loadmat(
            os.path.join(base, f"dataStim{subject}.mat"), simplify_cells=True
        )["stim"]
        names = np.atleast_1d(stim["condNames"])
        for trial, idx in enumerate(np.atleast_1d(stim["condIdxs"]), 1):
            out[(subject, trial)] = str(names[int(idx) - 1]).lower()
    return out


def aggregate(records: list[dict]) -> dict:
    subjects = sorted({r["subject"] for r in records}, key=str)
    rows = []
    for subject in subjects:
        rr = [r for r in records if r["subject"] == subject]
        normal = np.concatenate([r["normal"] for r in rr])
        neutral = np.concatenate([r["neutral"] for r in rr])
        rows.append({
            "subject": str(subject),
            "normal_acc1": float(normal.mean()),
            "dom0_acc1": float(neutral.mean()),
            "delta": float(neutral.mean() - normal.mean()),
            "n_frames": int(len(normal)),
        })
    return {
        "n_subjects": len(rows),
        "normal_acc1_subject_mean": float(np.mean([r["normal_acc1"] for r in rows])),
        "dom0_acc1_subject_mean": float(np.mean([r["dom0_acc1"] for r in rows])),
        "delta_subject_mean": float(np.mean([r["delta"] for r in rows])),
        "subjects": rows,
    }


def score_trials(dataset: str, trials, meta, nets) -> tuple[dict, list[dict]]:
    records = []
    t0 = time.time()
    for i, (tr, info) in enumerate(zip(trials, meta)):
        stim = tr["_S"]
        normal, starts = mean_logits(nets, tr["eeg"], stim)
        dom0 = stim.copy()
        dom0[:, :, -1] = 0
        neutral, starts0 = mean_logits(nets, tr["eeg"], dom0)
        if not np.array_equal(starts, starts0):
            raise RuntimeError("normal/dom0 frame grids differ")
        truth = tr["att"].astype(int)[np.maximum(starts - 32, 0)]
        sign = np.where(truth == 0, 1.0, -1.0)
        records.append({
            **info,
            "normal": normal * sign > 0,
            "neutral": neutral * sign > 0,
        })
        if (i + 1) % 40 == 0 or i + 1 == len(trials):
            print(f"{dataset}: {i + 1}/{len(trials)} ({time.time() - t0:.0f}s)", flush=True)
    return {
        "dataset": dataset,
        "n_trials": len(trials),
        **aggregate(records),
        "elapsed_s": time.time() - t0,
    }, records


def lodo_dataset(ds: str, conditions: dict) -> tuple[dict, list[dict]]:
    trials, meta = [], []
    for _, row in rows_of(ds).iterrows():
        tr = load_trial("eaP_n5_t60", row["key"])
        tr["_S"] = _targets(tr)
        info = {"subject": row["subj_uid"]}
        if ds == "KUL":
            info["condition"] = conditions[(int(row["subject"]), int(row["trial"]))]
        trials.append(tr)
        meta.append(info)
    nets = fold_nets(ds)
    result, records = score_trials(ds, trials, meta, nets)
    del nets
    torch.cuda.empty_cache()
    return result, records


def external_dataset(ds: str) -> dict:
    trials = E.ext_trials(ds)
    for tr in trials:
        tr["_S"] = external_targets(ds, tr)
    nets = load_nets()
    result, _ = score_trials(
        ds, trials, [{"subject": tr["subject"]} for tr in trials], nets
    )
    del nets
    torch.cuda.empty_cache()
    return result


def main() -> None:
    configure()
    os.makedirs(RUN_DIR, exist_ok=True)
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    conditions = kul_conditions()
    datasets, kul_records = {}, None
    for ds in DS_KEYS:
        datasets[ds], records = lodo_dataset(ds, conditions)
        if ds == "KUL":
            kul_records = records
    datasets.update({ds: external_dataset(ds) for ds in ("AASD", "Carta2026")})
    kul_split = {
        cond: aggregate([r for r in kul_records if r["condition"] == cond])
        for cond in sorted({r["condition"] for r in kul_records})
    }
    dry, hrtf = kul_split["dry"], kul_split["hrtf"]
    presentation_gap = (
        hrtf["normal_acc1_subject_mean"] - dry["normal_acc1_subject_mean"]
    )
    directional_ablation = (
        dry["delta_subject_mean"] >= 0 and hrtf["delta_subject_mean"] < 0
    )
    proceed = bool(presentation_gap >= 0.02 or directional_ablation)
    payload = {
        "run_id": RUN_ID,
        "status": "complete",
        "method": "frozen SW2 normal versus dom:=0; external labels report-only",
        "datasets": datasets,
        "KUL_by_presentation": kul_split,
        "decision": {
            "hrtf_minus_dry_normal_acc1": float(presentation_gap),
            "directional_ablation_pattern": bool(directional_ablation),
            "proceed": proceed,
            "next": "PAD_retrain" if proceed else "close_R2_ceiling",
        },
    }
    for path in (OUT, os.path.join(RUN_DIR, "metrics.json")):
        with open(path, "w") as fh:
            json.dump(payload, fh, indent=2)
    print(json.dumps(payload["decision"], indent=2), flush=True)


if __name__ == "__main__":
    main()
