"""Debug: why does the package VLAAI (vlaai.yaml) not learn? Short runs on one LODO fold (held-out KUL2016, mat prep,
the fold where the original never left loss 0), 8 epochs, no early stopping, one factor changed at a time.
Log: logs/debug_vlaai.log"""
import os, sys, time
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common_exp import CFG, EXP, load_trial, rows_of  # noqa: E402
from common import DS_KEYS  # noqa: E402
import decoders as D  # noqa: E402

HELD, PREP = "KUL", "mat"
LOG = open(os.path.join(EXP, "logs", "debug_vlaai.log"), "a", buffering=1)
def log(m):
    line = f"{time.strftime('%F %T')} {m}"; print(line, flush=True); LOG.write(line + "\n")

rng = np.random.default_rng(CFG["seed"] + DS_KEYS.index(HELD))
train, val = [], []
for ds in DS_KEYS:
    if ds == HELD: continue
    rows = rows_of(ds); vs = rng.choice(sorted(rows.subject.unique()))
    for _, r in rows.iterrows():
        (val if r["subject"] == vs else train).append(load_trial(PREP, r["key"]))
log(f"=== VLAAI ablation, held-out {HELD}, {len(train)} train / {len(val)} val trials")
VARIANTS = [
    ("orig: skip off, dropout 0.5, lr 5e-4", {}, {}),
    ("lr 1e-4", {}, {"lr": 1e-4}),
    ("dropout 0.0", {"dropout": 0.0}, {}),
    ("dropout 0.1", {"dropout": 0.1}, {}),
    ("skip on", {"use_skip": True}, {}),
    ("skip on + dropout 0.1", {"use_skip": True, "dropout": 0.1}, {}),
]
only = sys.argv[1:]
for tag, ov, dov in VARIANTS:
    if only and tag.split(":")[0] not in only: continue
    D.MODEL_OVERRIDES["vlaai"] = ov
    saved = {k: D.D[k] for k in ("max_epochs", "patience", "lr", "warmup_epochs") if k in D.D}
    D.D.update(max_epochs=8, patience=100, warmup_epochs=0, **dov)
    log(f"--- {tag}  model overrides {ov}  train overrides {dov}")
    dec = D.make("vlaai", train[0]["eeg"].shape[1], log)
    t0 = time.time(); best = dec.fit(train, val, None)
    log(f"--- {tag}: best val {best:+.4f} ({time.time() - t0:.0f}s)")
    D.D.update(saved)
log("=== done")
