#!/usr/bin/env bash
# Fake `pytest` binary for E2E tests.
# Protocol: see ./README.md
#
# Mirrors the canned-response + AUTODEV_FAKE_FAILURE_MODE convention used
# by fake-claude / fake-cursor so the orchestrator's test-engineer leg
# can be driven without a real pytest install. The "prompt" we hash is
# the joined non-flag positional argv (typically a path or test
# identifier), keeping the fake protocol consistent across all three
# binaries.
set -u

# --- collect a "prompt" out of pytest's argv ---------------------------------
# pytest takes a mix of flags and positional file/dir/nodeids. We keep the
# parsing intentionally loose: anything starting with `-` is skipped (its
# value is dropped on the floor), everything else is concatenated and used
# as the canned-response key.
prompt=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    -v|-q|--no-header|--no-summary|-s|-x|--tb=*|--maxfail=*|--co)
      shift
      ;;
    -k|-m|--rootdir|--basetemp|--junit-xml|--cov|--cov-report|--cov-config)
      # flag-with-value pairs; drop both
      shift 2 || shift
      ;;
    --version)
      echo "fake-pytest 0.0.0"
      exit 0
      ;;
    -*)
      shift
      ;;
    *)
      if [[ -z "$prompt" ]]; then
        prompt="$1"
      else
        prompt="$prompt $1"
      fi
      shift
      ;;
  esac
done

# --- failure mode short-circuits ---------------------------------------------
case "${AUTODEV_FAKE_FAILURE_MODE:-}" in
  no_tests_collected)
    printf 'collected 0 items\n\n=== no tests ran in 0.00s ===\n'
    exit 5
    ;;
  zero_pass_zero_fail)
    printf 'RESULTS: passed=0 failed=0 total=0\n'
    exit 0
    ;;
  collection_error)
    printf 'ERROR collecting tests:\nSyntaxError in test_foo.py line 5\n' >&2
    exit 1
    ;;
  runtime_crash)
    printf "ImportError: No module named 'foo_lib'\nTraceback (most recent call last):\n  File \"test_bar.py\", line 1, in <module>\n    import foo_lib\n" >&2
    exit 1
    ;;
  capture_failed)
    # Both stdout AND stderr empty; non-zero exit. Simulates a runner
    # whose output was lost (e.g. SIGKILLed before flushing buffers).
    exit 1
    ;;
esac

# --- canned response lookup ---------------------------------------------------
hash=""
if command -v md5sum >/dev/null 2>&1; then
  hash="$(printf '%s' "$prompt" | md5sum | awk '{print $1}')"
elif command -v md5 >/dev/null 2>&1; then
  hash="$(printf '%s' "$prompt" | md5 -q)"
fi
canned="${AUTODEV_FAKE_RESPONSE_DIR:-}/response_${hash}.json"
if [[ -n "$hash" && -f "$canned" ]]; then
  # Canned response file is taken verbatim — the test is responsible for
  # putting whatever stdout shape it wants in there.
  cat "$canned"
  exit 0
fi

# --- default success ----------------------------------------------------------
printf 'RESULTS: passed=3 failed=0 total=3\n'
exit 0
