#!/usr/bin/env bash
# Probe the stage-1 checkpoint, then train the one layer read the probe justifies.
# best.pth is deleted unless the official Score is above the stage-1 floor.
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}"
CKPT="${CKPT:-$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2/best.pth}"
PROBE_JSON="$ROOT/save/layer_probe_s1.json"
BOARD="$ROOT/save/layer_exp_board.json"
ORIG_DIR="$ROOT/save/icbhi_beats_frame_asd_frame_asd_F12_sastruct_s1_rerun2"

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

echo "=== Layer probe (checkpoint $CKPT) ==="
python -u scripts/probe_beats_layers.py \
  --resume "$CKPT" \
  --out "$PROBE_JSON" \
  --model beats --method frame_asd --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 \
  --test_fold official --pad_types repeat \
  --min_se 48 --min_sp 72 \
  --mil_pool topk --mil_topk 3 \
  --beats_wave_scale 32768 --threshold_n_points 41 \
  --num_workers 4
status=$?
if [[ "$status" -ne 0 ]]; then
  echo "Probe failed (exit $status)"
  exit "$status"
fi

read -r DECISION FEATURE_LAYER FEATURE_AUX REASON < <(python - "$PROBE_JSON" <<'PY'
import json, sys
data = json.load(open(sys.argv[1]))
print(data['decision'], data['feature_layer'], data['feature_layer_aux'], data['reason'].replace(' ', '_'))
PY
)
echo "Probe decision: $DECISION layer $FEATURE_LAYER aux $FEATURE_AUX"
echo "Reason: ${REASON//_/ }"
if [[ "$DECISION" == "stop" ]]; then
  echo "No layer gap. Not training."
  exit 0
fi

if [[ "$DECISION" == "layer" ]]; then
  TAG="frame_asd_F12_layer_${FEATURE_LAYER}"
elif [[ "$DECISION" == "concat" ]]; then
  TAG="frame_asd_F12_layercat_${FEATURE_AUX}"
else
  echo "Unknown decision $DECISION"
  exit 1
fi

OUT="$ROOT/save/icbhi_beats_frame_asd_${TAG}"
if [[ "$OUT" == "$ORIG_DIR" ]]; then
  echo "Refusing to write the stage-1 directory"
  exit 1
fi
mkdir -p "$OUT"
if [[ -f "$OUT/best.pth" ]]; then
  echo "$OUT/best.pth already exists; remove it or pick another TAG"
  exit 1
fi
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)"
  exit 1
fi

echo "=== Train $TAG (floor $FLOOR) ==="
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_${DECISION}" --epochs 15 --learning_rate 7e-5 \
  --freeze_backbone \
  --resume "$CKPT" \
  --resume_backbone_only \
  --reset_epoch_on_resume \
  --feature_layer "$FEATURE_LAYER" \
  --feature_layer_aux "$FEATURE_AUX" \
  2>&1 | tee "$OUT/train.log"
train_status=${PIPESTATUS[0]}
set -e
if [[ "$train_status" -ne 0 ]]; then
  echo "Train failed for $TAG (exit $train_status)"
  exit "$train_status"
fi

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
