#!/usr/bin/env bash
# Regression test for prompt-optimiser-directive.sh.
#
# Covers:
#   1. Valid UserPromptSubmit stdin  -> exit 0, stdout is valid JSON,
#      hookEventName == "UserPromptSubmit", additionalContext non-empty.
#   2. Empty / garbage stdin         -> exit 0, still valid JSON (the hook
#      ignores the prompt text; the directive is standing).
#   3. python3 unavailable on PATH   -> exit 0, empty stdout (fail-open).

set -u

HOOK="$(cd "$(dirname "$0")/.." && pwd)/prompt-optimiser-directive.sh"
if [[ ! -x "$HOOK" ]]; then
  echo "FAIL: $HOOK not executable" >&2
  exit 1
fi

PASS=0
FAIL=0

# Assert: hook on $1 (stdin) exits 0 and stdout is JSON with a non-empty
# additionalContext and the correct hookEventName.
assert_valid_injection() {
  local name="$1" stdin="$2" out actual_exit
  out=$(printf '%s' "$stdin" | bash "$HOOK" 2>/dev/null)
  actual_exit=$?
  if [[ "$actual_exit" -ne 0 ]]; then
    echo "FAIL: $name (expected exit=0, got=$actual_exit)" >&2; FAIL=$((FAIL+1)); return
  fi
  if printf '%s' "$out" | python3 -c '
import json, sys
d = json.load(sys.stdin)
h = d["hookSpecificOutput"]
assert h["hookEventName"] == "UserPromptSubmit", "wrong hookEventName"
assert isinstance(h["additionalContext"], str) and len(h["additionalContext"]) > 0, "empty additionalContext"
' 2>/dev/null; then
    echo "PASS: $name"; PASS=$((PASS+1))
  else
    echo "FAIL: $name (stdout not valid directive JSON: $out)" >&2; FAIL=$((FAIL+1))
  fi
}

# Case 1 — valid UserPromptSubmit envelope.
assert_valid_injection "valid UserPromptSubmit stdin -> directive JSON" \
  '{"hook_event_name":"UserPromptSubmit","prompt":"fix the thing","session_id":"abc"}'

# Case 2 — garbage stdin still yields the standing directive.
assert_valid_injection "garbage stdin -> still directive JSON" \
  'not json at all'

# Case 3 — fail-open when python3 is absent from PATH.
FAKEBIN=$(mktemp -d)
# A minimal PATH containing the core utils the hook needs (cat, printf, env,
# command) but NOT python3. Resolve their real dir(s) and symlink them in.
for util in cat printf env bash; do
  src=$(command -v "$util" 2>/dev/null) && ln -sf "$src" "$FAKEBIN/$util" 2>/dev/null
done
nopy_out=$(printf '%s' '{"prompt":"x"}' | PATH="$FAKEBIN" bash "$HOOK" 2>/dev/null)
nopy_exit=$?
if [[ "$nopy_exit" -eq 0 && -z "$nopy_out" ]]; then
  echo "PASS: python3 absent -> exit 0, empty stdout (fail-open)"; PASS=$((PASS+1))
else
  echo "FAIL: python3 absent (expected exit=0 + empty stdout, got exit=$nopy_exit stdout=$nopy_out)" >&2; FAIL=$((FAIL+1))
fi
rm -rf "$FAKEBIN"

echo "----"
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
