#!/usr/bin/env bash
#
# Run repeated PoC FDP WAF comparisons under one fixed configuration.

set -Eeuo pipefail

export REPEATS="${REPEATS:-3}"
export OUT="${OUT:-$HOME/fdp_measure_repeats}"
export ORDER_STRATEGY="${ORDER_STRATEGY:-rotate}"
export MODE_SEQUENCE="${MODE_SEQUENCE:-no_fdp,mixed,separated}"
export RUN_R0_EACH_MODE="${RUN_R0_EACH_MODE:-0}"

IFS=',' read -r -a BASE_MODES <<< "$MODE_SEQUENCE"
if [ "${#BASE_MODES[@]}" -ne 3 ]; then
  echo "MODE_SEQUENCE must contain exactly three comma-separated modes" >&2
  exit 2
fi

for mode in "${BASE_MODES[@]}"; do
  case "$mode" in
    no_fdp|separated|mixed) ;;
    *)
      echo "invalid mode in MODE_SEQUENCE: $mode" >&2
      exit 2
      ;;
  esac
done

batch_id="batch_$(date +%Y%m%dT%H%M%S)"
batch_dir="$OUT/$batch_id"
mkdir -p "$batch_dir"

{
  echo "# repeated trials"
  date -Is
  echo "repeats=$REPEATS"
  echo "order_strategy=$ORDER_STRATEGY"
  echo "mode_sequence=$MODE_SEQUENCE"
  echo "run_r0_each_mode=$RUN_R0_EACH_MODE"
  echo "out=$batch_dir"
} | tee "$batch_dir/batch.log"

printf "trial,position,mode\n" > "$batch_dir/trial_plan.csv"

rotate_modes() {
  local shift="$1"
  local count="${#BASE_MODES[@]}"
  local idx
  for ((idx = 0; idx < count; idx++)); do
    printf '%s\n' "${BASE_MODES[$(((idx + shift) % count))]}"
  done
}

for trial in $(seq 1 "$REPEATS"); do
  trial_id=$(printf "trial_%02d" "$trial")
  trial_dir="$batch_dir/$trial_id"
  mkdir -p "$trial_dir"

  case "$ORDER_STRATEGY" in
    fixed)
      mapfile -t modes < <(printf '%s\n' "${BASE_MODES[@]}")
      ;;
    rotate)
      mapfile -t modes < <(rotate_modes "$((trial - 1))")
      ;;
    *)
      echo "unsupported ORDER_STRATEGY: $ORDER_STRATEGY" >&2
      exit 2
      ;;
  esac

  {
    echo ""
    echo "[$trial_id] start $(date -Is)"
    printf '[%s] modes=%s\n' "$trial_id" "$(IFS=,; echo "${modes[*]}")"
  } | tee -a "$batch_dir/batch.log"

  for pos in "${!modes[@]}"; do
    mode="${modes[$pos]}"
    printf "%s,%d,%s\n" "$trial_id" "$((pos + 1))" "$mode" >> "$batch_dir/trial_plan.csv"
    {
      echo "[$trial_id] position=$((pos + 1)) mode=$mode start $(date -Is)"
    } | tee -a "$batch_dir/batch.log"
    if [ "$RUN_R0_EACH_MODE" = "1" ]; then
      OUT="$trial_dir" bash "$(dirname "$0")/run_R0_precondition.sh" \
        2>&1 | tee -a "$batch_dir/batch.log"
    fi
    OUT="$trial_dir" bash "$(dirname "$0")/run_poc_harness.sh" "$mode" \
      2>&1 | tee -a "$batch_dir/batch.log"
    {
      echo "[$trial_id] position=$((pos + 1)) mode=$mode end $(date -Is)"
    } | tee -a "$batch_dir/batch.log"
  done

  /usr/bin/python3 "$(dirname "$0")/parse_results.py" "$trial_dir" \
    > "$trial_dir/results_summary.csv"
  /usr/bin/python3 "$(dirname "$0")/write_report.py" "$trial_dir" \
    > "$trial_dir/report.md"
done

/usr/bin/python3 "$(dirname "$0")/summarize_repeated_trials.py" "$batch_dir" \
  > "$batch_dir/repeated_summary.csv"

echo "[repeat] complete: $batch_dir"
