#!/usr/bin/env bash
# Wait for gpu.lock (stem-sw2-ms may hold it), then run xcorr-matched-clf.
set -euo pipefail
cd /root/disk_3tb/eeg-thao
export GLIMPSE_THR=norm PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=8 MKL_NUM_THREADS=8
PY=/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/.venv/bin/python
LOG=experiments/xcorr_matched_lodo_console.log
mkdir -p experiments models/xcorr results/research multi_agent_opt

exec 9>multi_agent_opt/gpu.lock
tries=0
while ! flock -n 9; do
  tries=$((tries + 1))
  if (( tries % 6 == 1 )); then
    echo "$(date -Is) waiting GPU (try $tries); stem-sw2 last:" | tee -a "$LOG"
    tail -n 2 experiments/stem_sw2_ms_console.log 2>/dev/null || \
      tail -n 2 experiments/*sw2*ms* 2>/dev/null || \
      echo "(no stem-sw2 console yet)" | tee -a "$LOG"
    pgrep -af 'stem_sw2|sw2_ms|stem-sw2' | head -3 || echo 'no stem-sw2 proc' | tee -a "$LOG"
  fi
  sleep 20
done
echo "GPU lock acquired pid=$$ at $(date -Is)" | tee -a "$LOG"
nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv | tee -a "$LOG"

# Mark CLAIMS running
python3 - <<'PY'
from pathlib import Path
from datetime import datetime, timezone, timedelta
p = Path("multi_agent_opt/CLAIMS.md")
t = p.read_text()
old = "| xcorr-matched-clf | Causal multi-lag EEG↔envelope cross-corr features → small antisymmetric DirectNet head; eaP; swap+chance abort; LODO+ext if learns | claimed |"
new = "| xcorr-matched-clf | Causal multi-lag EEG↔envelope cross-corr features → small antisymmetric DirectNet head; eaP; swap+chance abort; LODO+ext if learns | running |"
if old in t:
    p.write_text(t.replace(old, new, 1))
    print("claim -> running")
else:
    # softer match
    lines = []
    for line in t.splitlines():
        if "| xcorr-matched-clf |" in line and "| claimed |" in line:
            line = line.replace("| claimed |", "| running |", 1)
            print("claim -> running (soft)")
        lines.append(line)
    p.write_text("\n".join(lines) + ("\n" if t.endswith("\n") else ""))
PY

BATCH=${BATCH:-64}
set +e
BATCH=$BATCH $PY -u xcorr_matched_lodo.py 2>&1 | tee -a "$LOG"
EC=${PIPESTATUS[0]}
if [[ $EC -eq 2 ]]; then
  echo "retry BATCH=32" | tee -a "$LOG"
  BATCH=32 $PY -u xcorr_matched_lodo.py 2>&1 | tee -a "$LOG"
  EC=${PIPESTATUS[0]}
fi
echo "EXIT:$EC at $(date -Is)" | tee -a "$LOG"

# Update CLAIMS done/abandoned from JSON if present
python3 - <<'PY'
import json
from pathlib import Path
jp = Path("results/direct_clf__eaP_n5_t60_w10_xcorr_aug-sw2.json")
md = Path("multi_agent_opt/CLAIMS.md")
t = md.read_text()
status = "done"
note = "see results_xcorr_matched.md"
if jp.exists():
    d = json.load(open(jp))
    status = d.get("status", "done")
    if status == "abandoned":
        st = d.get("swap_test", {})
        note = (f"swapΔ={st.get('delta')}; {d.get('reason')}. "
                f"`results_xcorr_matched.md`.")
    else:
        note = (f"LODO mean H {d.get('mean_H')} Acc {d.get('mean_Acc')}. "
                f"`results_xcorr_matched.md`.")
lines = []
for line in t.splitlines():
    if "| xcorr-matched-clf |" in line and ("| running |" in line or "| claimed |" in line):
        parts = line.split("|")
        # | when | agent | method | status | note |
        if len(parts) >= 6:
            parts[4] = f" {status} "
            parts[5] = f" {note} "
            line = "|".join(parts)
        print(f"claim -> {status}")
    lines.append(line)
md.write_text("\n".join(lines) + "\n")

# ALREADY_TRIED append
already = Path("multi_agent_opt/ALREADY_TRIED.md")
blob = already.read_text() if already.exists() else ""
marker = "**xcorr-matched**"
if marker not in blob:
    add = (
        "\n- **xcorr-matched** 10 s DirectNet (`decoders.XCorrMatched`; multi-lag "
        "EEG↔env xcorr → CNN; eaP_n5_t60 sw2 light init). "
        f"{note} Do not rerun identical xcorr bank. "
        "`multi_agent_opt/results_xcorr_matched.md`.\n"
    )
    already.write_text(blob.rstrip() + "\n" + add)

# STATUS_GAPS: mark xcorr closed
sg = Path("multi_agent_opt/STATUS_GAPS.md")
if sg.exists():
    s = sg.read_text()
    s2 = s.replace(
        "2. **xcorr-matched-clf** — claimed after stem-sw2-ms (new xcorr backbone).",
        f"2. **xcorr-matched-clf** — {status}: {note}",
    )
    if s2 == s:
        s2 = s.replace(
            "3. **xcorr-matched-clf** — claimed after stem-sw2-ms (new xcorr backbone).",
            f"3. **xcorr-matched-clf** — {status}: {note}",
        )
    sg.write_text(s2)
print("CLAIMS/ALREADY/STATUS updated")
PY

exit $EC
