#!/usr/bin/env bash
set -euo pipefail

# Run the warm laptop gate here and a caller-supplied cold-pod command (normally
# `gh workflow run` + check watcher or a cluster wrapper) from the same revision.
# The harness deliberately does not claim evidence when no cluster command exists.
COLD_POD_COMMAND=${COLD_POD_COMMAND:-}
WARM_LAPTOP_COMMAND=${WARM_LAPTOP_COMMAND:-bun test --timeout 20000}
[[ -n "$COLD_POD_COMMAND" ]] || {
  echo "measurement unavailable: set COLD_POD_COMMAND to a command that blocks until the cold runner pod's collector gate completes" >&2
  exit 2
}

measure_ms() {
  local label=$1 command=$2 start end status
  start=$(date +%s%N)
  set +e
  (cd collector && bash -lc "$command")
  status=$?
  set -e
  end=$(date +%s%N)
  elapsed=$(( (end - start) / 1000000 ))
  printf -v "$label" '%s' "$elapsed"
  (( status == 0 )) || { echo "$label command failed with status $status after ${elapsed}ms" >&2; exit "$status"; }
}

measure_ms warm_laptop_ms "$WARM_LAPTOP_COMMAND"
measure_ms cold_pod_ms "$COLD_POD_COMMAND"
ratio=$(awk -v cold="$cold_pod_ms" -v warm="$warm_laptop_ms" 'BEGIN { if (warm == 0) exit 1; printf "%.2f", cold / warm }')
printf 'warm_laptop_ms=%s\ncold_pod_ms=%s\ncold_to_warm_ratio=%s\ntarget_ratio_max=2.00\n' \
  "$warm_laptop_ms" "$cold_pod_ms" "$ratio"
awk -v ratio="$ratio" 'BEGIN { exit !(ratio <= 2.0) }'
