#!/usr/bin/env bash
# One-change stage-1 runs. Keep best.pth only when Score is above the F12 floor.
# Does not call scripts/f12_s1.sh and does not touch that reference log.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

SEED="${SEED:-1}"
BATCH_SIZE="${BATCH_SIZE:-16}"
FLOOR="${FLOOR:-66.32}"
MIN_FREE_MB="${MIN_FREE_MB:-1500}"
BOARD="$ROOT/save/s1_sweep_board.json"
ORIG_DIR="$ROOT/icbhi_beats_frame_asd_F12_s1"

[[ -f "$ROOT/pretrained_models/BEATs_iter3_plus_AS2M.pt" ]] || { echo "Missing pretrained_models/BEATs_iter3_plus_AS2M.pt"; exit 1; }
[[ -f "$ORIG_DIR/train.log" ]] || { echo "Missing reference log $ORIG_DIR/train.log"; exit 1; }
mkdir -p "$ROOT/save"
if [[ ! -f "$BOARD" ]]; then
  echo '[]' > "$BOARD"
fi

run_one() {
  local name="$1"
  shift
  local tag="frame_asd_F12_s1exp_${name}"
  local out="$ROOT/save/icbhi_beats_frame_asd_${tag}"
  if [[ "$out" == "$ORIG_DIR" || "$tag" == "frame_asd_F12_restore_sastruct_s1" ]]; then
    echo "Refusing to write the F12 reference directory"
    return 1
  fi
  mkdir -p "$out"
  if [[ -f "$out/train.log" ]] && grep -q '^Finished\. Best Score:' "$out/train.log"; then
    echo "=== $tag already finished; applying keep rule ==="
    record_one "$tag" "$out"
    return 0
  fi
  local free_mb
  free_mb=$(df --output=avail -BM "$ROOT/save" | tail -1 | tr -dc '0-9')
  if (( free_mb < MIN_FREE_MB )); then
    echo "Only ${free_mb}MB free (need >= ${MIN_FREE_MB}MB)"
    record_fail "$tag" "$out" "disk"
    return 0
  fi
  rm -f "$out/best.pth"
  echo "=== F12 sweep $tag (seed $SEED) ==="
  set +e
  python -u train.py --tag "$tag" \
    --method frame_asd --model beats --dataset icbhi --seed "$SEED" \
    --save_dir "$ROOT/save" \
    --class_split lungsound --n_cls 4 --batch_size "$BATCH_SIZE" \
    --desired_length 5 --optimizer adam --weight_decay 1e-6 \
    --cosine --test_fold official --pad_types repeat \
    --ma_update --ma_beta 0.5 --print_freq 50 \
    --min_se 48 --min_sp 72 --early_stop_patience 8 \
    --mil_pool topk --mil_topk 3 \
    --use_specaug --specaug_policy structured \
    --beats_wave_scale 32768 --threshold_n_points 41 \
    --ablation_stage "F12_s1exp_${name}" --epochs 15 --learning_rate 7e-5 \
    "$@" 2>&1 | tee "$out/train.log"
  local status=${PIPESTATUS[0]}
  if [[ "$status" -ne 0 ]]; then
    echo "Run failed for $tag (exit $status)"
    record_fail "$tag" "$out" "exit ${status}"
    return 0
  fi
  record_one "$tag" "$out"
}

record_one() {
  local tag="$1"
  local out="$2"
  python - "$BOARD" "$tag" "$out" "$FLOOR" <<'PY'
import json, os, sys
board_path, tag, out, floor = sys.argv[1:5]
floor = float(floor)
thr_path = os.path.join(out, 'best_threshold.json')
entry = {'tag': tag, 'dir': out, 'score': None, 'sp': None, 'se': None, 'kept': False}
if os.path.isfile(thr_path):
    data = json.load(open(thr_path))
    entry['score'] = float(data['score'])
    entry['sp'] = float(data['sp'])
    entry['se'] = float(data['se'])
    entry['kept'] = entry['score'] > floor
ckpt = os.path.join(out, 'best.pth')
if entry['kept']:
    print('KEEP {} Score {:.2f} Sp {:.1f} Se {:.1f}'.format(
        tag, entry['score'], entry['sp'], entry['se']))
elif os.path.isfile(ckpt):
    os.remove(ckpt)
    shown = entry['score'] if entry['score'] is not None else float('nan')
    print('DROP checkpoint {} Score {:.2f} is not above {:.2f}'.format(tag, shown, floor))
else:
    print('DROP {} no checkpoint (score {})'.format(tag, entry['score']))
board = json.load(open(board_path)) if os.path.isfile(board_path) else []
board = [row for row in board if row.get('tag') != tag]
board.append(entry)
with open(board_path, 'w') as handle:
    json.dump(board, handle, indent=2)
PY
}

record_fail() {
  local tag="$1"
  local out="$2"
  local reason="$3"
  python - "$BOARD" "$tag" "$out" "$reason" <<'PY'
import json, os, sys
board_path, tag, out, reason = sys.argv[1:5]
entry = {
    'tag': tag, 'dir': out, 'score': None, 'sp': None, 'se': None,
    'kept': False, 'error': reason,
}
ckpt = os.path.join(out, 'best.pth')
if os.path.isfile(ckpt):
    os.remove(ckpt)
board = json.load(open(board_path)) if os.path.isfile(board_path) else []
board = [row for row in board if row.get('tag') != tag]
board.append(entry)
with open(board_path, 'w') as handle:
    json.dump(board, handle, indent=2)
print('DROP {} ({})'.format(tag, reason))
PY
}

run_one mlp --head_type mlp --learning_rate 7e-5
run_one both --lambda_both 0.1
run_one focal --wheeze_focal
run_one lr --learning_rate 1e-4
run_one energy --mil_energy_guided
run_one pcsl --lambda_pcsl 0.1

echo "Sweep board: $BOARD"
python - "$BOARD" <<'PY'
import json, sys
board = json.load(open(sys.argv[1]))
kept = [row for row in board if row.get('kept')]
print('Kept {} of {}'.format(len(kept), len(board)))
for row in board:
    score = row.get('score')
    score_s = '-' if score is None else '{:.2f}'.format(score)
    print('{} {} Score {}'.format('KEEP' if row.get('kept') else 'DROP', row['tag'], score_s))
PY
