#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

ORIG_TAG=frame_asd_F12_restore_sastruct_s1
TAG="${TAG:-frame_asd_F12_sastruct_s1_rerun}"
SEED="${SEED:-1}"
BATCH_SIZE="${BATCH_SIZE:-16}"
MIN_FREE_MB="${MIN_FREE_MB:-1500}"
ORIG_DIR="$ROOT/icbhi_beats_frame_asd_F12_s1"
OUT="$ROOT/save/icbhi_beats_frame_asd_${TAG}"

[[ "$TAG" != "$ORIG_TAG" ]] || { echo "TAG must differ from $ORIG_TAG (would overwrite the 66.32 checkpoint)"; exit 1; }
[[ -f "$ORIG_DIR/train.log" ]] || { echo "Missing reference log $ORIG_DIR/train.log"; 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
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 $TAG (seed $SEED, ${FREE_MB}MB free) ==="
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 --epochs 15 --learning_rate 7e-5 2>&1 | tee "$OUT/train.log"
[[ -f "$OUT/best.pth" ]] || { echo "No best.pth produced for $TAG"; exit 1; }

python - "$ORIG_DIR" "$OUT" <<'EOF'
import json, os, re, sys
orig, new = sys.argv[1:3]
pat = re.compile(
    r'^Val: Score ([\d.]+) Sp ([\d.]+) Se ([\d.]+).*?n→whe_fp (\d+)',
    re.M)

def val(d):
    text = open(os.path.join(d, 'train.log'), encoding='utf-8').read()
    rows = []
    for match in pat.finditer(text):
        score, sp, se, fp = match.groups()
        rows.append((float(score), float(sp), float(se), int(fp)))
    return rows

def fmt(row):
    if row is None:
        return '-'
    return '{:6.2f} {:6.1f} {:6.1f} {:>4d}'.format(*row)

a, b = val(orig), val(new)
print('\n{:>5} | {:>26} | {:>26} | {:>6} | {:>5}'.format(
    'epoch', 'original Score/Sp/Se/fp', 'rerun Score/Sp/Se/fp', 'dScore', 'dfp'))
mismatches = []
for i in range(max(len(a), len(b))):
    left = a[i] if i < len(a) else None
    right = b[i] if i < len(b) else None
    d_score = ''
    d_fp = ''
    if left is not None and right is not None:
        d_score = '{:+.2f}'.format(right[0] - left[0])
        d_fp = '{:+d}'.format(right[3] - left[3])
        if left[0] != right[0] or left[3] != right[3]:
            mismatches.append(i + 1)
    else:
        mismatches.append(i + 1)
    print('{:>5} | {:>26} | {:>26} | {:>6} | {:>5}'.format(
        i + 1, fmt(left), fmt(right), d_score, d_fp))
n = min(len(a), len(b))
max_diff = max((abs(a[i][0] - b[i][0]) for i in range(n)), default=0.0)
best = lambda d: json.load(open(os.path.join(d, 'best_threshold.json')))['score']
same = not mismatches
print('\nbest: original {:.2f} | rerun {:.2f} | max |dScore| over {} common epochs: {:.2f} ({})'.format(
    best(orig), best(new), n, max_diff, 'identical' if same else 'differs'))
if mismatches:
    print('Score or n→whe_fp differs at epochs: {}'.format(
        ', '.join(str(epoch) for epoch in mismatches)))
    sys.exit(1)
EOF
