#!/bin/bash
# =============================================================================
# crossre_scratch.sh — Cross-Re From-Scratch Training
#
# Trains re60/re200/re400 from scratch on single GPU, serially.
# Uses generic SIM_BP, K_CD/CL=50/100, lr=3e-4.
# Output: output/kar_{re60,re200,re400}_seed43/
#
# Usage:
#   bash crossre_scratch.sh [--gpu 0] [--episodes 500]
#   bash crossre_scratch.sh --only re200
# =============================================================================
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TRAIN_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_DIR="$(cd "$TRAIN_DIR/../../.." && pwd)"
CONDA_ENV="pycuda_3_10"
registry() { PYTHONPATH="$REPO_DIR/src" python3 -m drl_pinball.train.case_registry "$CASE" "$1"; }
GPU=0; EPISODES=500; DELAY=120; ONLY=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --gpu) GPU="$2"; shift 2 ;;
        --episodes) EPISODES="$2"; shift 2 ;;
        --only) ONLY="$2"; shift 2 ;;
        *) echo "Unknown: $1"; exit 1 ;;
    esac
done

echo "=== Cross-Re Scratch: GPU=$GPU, ep=$EPISODES ==="

for re in re60 re200 re400; do
    [[ -n "$ONLY" && "$ONLY" != "$re" ]] && continue
    CASE="kar_${re}"
    CAL="$(registry calibration)"
    CFG="$(registry config)"
    TRAINER="$(registry trainer)"
    SEED="$(registry seeds)"
    echo "  [$(date '+%H:%M:%S')] Training $CASE..."
    conda run --no-capture-output -n "$CONDA_ENV" python -u \
        "$TRAINER" \
        --case-name "$CASE" --device-id "$GPU" --seed "$SEED" \
        --config "$CFG" --calibration "$CAL" \
        --total-episodes "$EPISODES" --lr 0.0003
    echo "  [$(date '+%H:%M:%S')] $CASE done. Sleeping ${DELAY}s..."
    sleep "$DELAY"
done
echo "=== All done ==="
