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

root="$(cd "$(dirname "$0")" && pwd)"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/bin" "$tmp/home" "$tmp/ws"

# Stub engine: create-chat plus three output shapes ca.sh must classify.
cat >"$tmp/bin/cursor-agent" <<'STUB'
#!/usr/bin/env bash
if [[ "${1:-}" == "create-chat" ]]; then echo chat-test; exit 0; fi
if [[ "${1:-}" == "status" ]]; then printf '%s\n' '{}'; exit 0; fi
case "${CA_TEST_MODE:-large}" in
  empty) printf '   \n\t\n  \n'; exit 0;;
  rate)  printf 'error: 429 Too Many Requests\n'; exit 1;;
  *)     yes '{"type":"assistant","text":"שלום עולם padding padding padding padding"}' | head -n 30000; exit 0;;
esac
STUB
chmod +x "$tmp/bin/cursor-agent"

run_case() {
  local mode="$1"
  rm -rf "${tmp:?}/home/Projects"
  env -i \
    HOME="$tmp/home" \
    PATH="$tmp/bin:/usr/bin:/bin" \
    LANG=en_IL LC_CTYPE=en_IL \
    CA_TEST_MODE="$mode" \
    bash "$root/ca.sh" \
      --workspace "$tmp/ws" \
      --trust 'classification fixture' \
      --task-slug catest \
      --model composer-2.5 \
      --timeout 120 >/dev/null 2>&1
}

fail() { printf 'FAIL %s\n' "$1" >&2; exit 1; }

# Agent output must never be held in a shell variable: bash pattern substitution
# over it spins in the multibyte path. Classification reads the file instead.
if grep -q 'raw_output' "$root/ca.sh"; then fail "ca.sh reintroduced a raw_output shell variable"; fi
if grep -qE '\$\(cat "\$RAW_OUTPUT_FILE"\)' "$root/ca.sh"; then fail "ca.sh reintroduced a whole-file slurp"; fi

# Multi-MB output with multibyte characters must classify in bounded time.
# The removed `${raw_output//[[:space:]]/}` spun for hours on this input.
start=$EPOCHREALTIME
rc=0; run_case large || rc=$?
elapsed=$(( ${EPOCHREALTIME%.*} - ${start%.*} ))
[[ $rc -eq 0 ]] || fail "large output: expected exit 0, got $rc"
[[ $elapsed -lt 30 ]] || fail "large output: classification took ${elapsed}s (unbounded regression)"
bytes=$(cat "$tmp/home/Projects/mega-plan-harness/tmp/logs/"*catest.raw | wc -c)
[[ $bytes -gt 1000000 ]] || fail "fixture too small (${bytes} bytes) to exercise the regression"

rc=0; run_case empty || rc=$?
[[ $rc -eq 3 ]] || fail "whitespace-only output: expected exit 3, got $rc"

rc=0; run_case rate || rc=$?
[[ $rc -eq 75 ]] || fail "rate-limited output: expected exit 75, got $rc"

printf 'PASS ca.sh classifies %s-byte output in %ss; empty=3 rate=75\n' "$bytes" "$elapsed"
