#!/bin/bash
# Run a bake-off under bash and record the python exit code after tee.
#
#   ./run-bakeoff.sh --self-test             check the direct bench against a scripted fake Ollama first
#   ./run-bakeoff.sh [args...]               direct Ollama bench (bakeoff_7.py): runtime, harness-wire, card rows
#   ./run-bakeoff.sh --harness --self-test   check the product lane (needs the .app or --bin)
#   ./run-bakeoff.sh --harness [args...]     the product test through CG Agent Harness (bakeoff_harness.py)
#
# Preflight, before any model run (self-test and --dry-run skip it):
#   * AC power. A run on battery is refused (BAKEOFF_ALLOW_BATTERY=1 overrides; speeds are then labeled dirty).
#   * Nothing listening on 127.0.0.1:8790. The app's warmup can reload qwen3.8:27b-mlx under the bench.
#     Quit CG Agent Harness first (BAKEOFF_ALLOW_APP=1 overrides).
#   * OLLAMA_CONTEXT_LENGTH: the scripts read the tag's own PARAMETER num_ctx, so an environment 32768
#     cannot pass an unpinned tag; it is reported, not changed. The harness lane still needs every model it
#     scores to load 32768 with no num_ctx, from the tag or that variable.
#
# Outsiders: the login shell on this Mac is zsh. Grok Build runs its commands
# in zsh as well. zsh stores pipeline statuses in pipestatus, starting at 1.
# bash stores them in PIPESTATUS, starting at 0. zsh leaves PIPESTATUS unset,
# so a line like echo "BAKEOFF_EXIT:${PIPESTATUS[0]}" writes nothing after
# the colon. A watcher then reports an unknown exit even when python exited 0.
#
# The shebang above is the whole fix. This process is bash. The Terminal
# login shell stays zsh. This file does not edit ~/.zshrc, ~/.zprofile, or
# ~/.shell_common, and it does not change bash for any other program.
#
# Read PIPESTATUS on the next lines. Any later command replaces that array.
# [0] is python (caffeinate passes its exit through). [1] is tee. pipefail
# still makes this script's own exit status non-zero when either side fails.

set -o pipefail
here=$(cd "$(dirname "$0")" && pwd)
script=bakeoff_7.py
tag=bakeoff7
if [ "${1:-}" = "--harness" ]; then
  shift
  script=bakeoff_harness.py
  tag=bakeoff-harness
fi
log=${BAKEOFF_LOG:-/tmp/$tag-run.log}

preflight=1
app_state="8790 free"
power_state="power unknown (no pmset)"
for a in "$@"; do
  case "$a" in --self-test|--dry-run|-h|--help) preflight=0 ;; esac
done
if [ "$preflight" = 1 ]; then
  if command -v pmset >/dev/null 2>&1; then
    power=$(pmset -g batt | head -1)
    case "$power" in
      *"AC Power"*) power_state="AC power" ;;
      *) if [ "${BAKEOFF_ALLOW_BATTERY:-0}" != 1 ]; then
           echo "preflight: not on AC power ($power). Plug in, or set BAKEOFF_ALLOW_BATTERY=1 (speeds become dirty)." >&2
           exit 3
         fi
         power_state="ON BATTERY (allowed; speeds dirty)" ;;
    esac
  fi
  if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:8790 -sTCP:LISTEN >/dev/null 2>&1; then
    if [ "${BAKEOFF_ALLOW_APP:-0}" != 1 ]; then
      echo "preflight: something listens on 127.0.0.1:8790 (CG Agent Harness?). Quit it, or set BAKEOFF_ALLOW_APP=1." >&2
      exit 3
    fi
    app_state="8790 IN USE (allowed; speeds dirty)"
  fi
  ctx_env=${OLLAMA_CONTEXT_LENGTH:-$(launchctl getenv OLLAMA_CONTEXT_LENGTH 2>/dev/null)}
  echo "preflight: $power_state; $app_state; OLLAMA_CONTEXT_LENGTH=${ctx_env:-unset} (reported, tag pins are read from /api/show)"
fi

# caffeinate: -i idle sleep, -m disk sleep, -s system sleep on AC. Absent off macOS.
runner=()
command -v caffeinate >/dev/null 2>&1 && runner=(caffeinate -ims)
${runner[@]+"${runner[@]}"} python3 "$here/$script" "$@" 2>&1 | tee "$log"
# One assignment. The next simple command replaces PIPESTATUS.
statuses=("${PIPESTATUS[@]}")
py_status=${statuses[0]}
tee_status=${statuses[1]}
printf 'BAKEOFF_EXIT:%s\n' "$py_status" | tee -a "$log"
printf 'BAKEOFF_TEE:%s\n' "$tee_status" | tee -a "$log"
exit "$py_status"
