#!/usr/bin/env bash
# Stage 2 only. Stage 1 is scripts/f12_s1.sh via train.py.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

TAG="${TAG:-frame_asd_F12_feedback_s2_resp}"
SEED="${SEED:-1}"
BATCH_SIZE="${BATCH_SIZE:-16}"
MIN_FREE_MB="${MIN_FREE_MB:-1500}"
RESUME="${RESUME:-$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2/best.pth}"
OUT="$ROOT/save/icbhi_beats_frame_asd_${TAG}"

[[ -n "$RESUME" && -f "$RESUME" ]] || { echo "Set RESUME to an F12 best.pth"; exit 1; }
[[ -f "$ROOT/pretrained_models/BEATs_iter3_plus_AS2M.pt" ]] || { echo "Missing pretrained_models/BEATs_iter3_plus_AS2M.pt"; exit 1; }
if [[ -f "$OUT/best.pth" ]]; then
  echo "$OUT/best.pth already exists; remove it or pick another TAG"
  exit 1
fi
mkdir -p "$ROOT/save"
FREE_MB=$(df --output=avail -BM "$ROOT/save" | tail -1 | tr -dc '0-9')
(( FREE_MB >= MIN_FREE_MB )) || { echo "Only ${FREE_MB}MB free (need >= ${MIN_FREE_MB}MB)"; exit 1; }
mkdir -p "$OUT"

echo "=== F12 feedback stage 2 $TAG (seed $SEED, resume $RESUME) ==="
python -u train_feedback.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 \
  --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_feedback_s2 \
  --feedback_slots 4 --feedback_layers 2 --feedback_drop 0.2 \
  --reason_codes 16 --lambda_consistency 0.1 --lambda_reason 0 \
  --w_wheeze 1.0 --lambda_both 0 \
  --ma_update --ma_beta 0.5 \
  --epochs 15 \
  --resume "$RESUME" 2>&1 | tee "$OUT/train.log"
[[ -f "$OUT/best.pth" ]] || { echo "No best.pth produced for $TAG"; exit 1; }
