#!/usr/bin/env bash
# CHECK-q153 -- a beam test that graded a file nobody committed, repaired, and
# the lane gate that now reds on the class before it lands.
#
# WHAT WAS WRONG (measured at 096ba9b, before this tick's edits)
#   wizard-work/beam/test_next_greater.py:3 was
#   `sys.path.insert(0, "/root/.hermes/wizard-outputs/beam")`. The host copy and
#   the tree copy were byte-identical (sha256 f015c464...), so nothing looked
#   wrong: run from a directory holding no next_greater.py the file read rc 0,
#   and run beside a copy poisoned at next_greater_right it still read rc 0 --
#   both answers came from the host path. On any other host the cell could not
#   grade at all (ModuleNotFoundError). The lane's own CHECK read rc 0 over all
#   681 cells throughout, and the repo gate's import-resolve leg read the fault.
#
# WHAT THIS GRADES
#   1. wizard-work/volt/q153_verify.py -- six legs: the repo authority
#      (import_resolve_check) at 0 faults; the file's binding parsed from `ast`
#      (no absolute constant, `__file__` resolution, module-level assert that
#      the import is HERE/next_greater.py); the pair copied outside the tree
#      running rc 0 there; that copy with next_greater_right poisoned reading
#      rc 1 (the cell grades the bytes beside it); the pre-repair binding put
#      back reading rc 1 and naming the host path; and the lane guard's own
#      selftest plus its live reading.
#   2. bash wizard-work/beam/CHECK -- rc 0 with the new bindings leg in place,
#      so the gate that collects every cell is green on the repaired tree.
#
#   rc 0 every leg holds   rc 1 a leg failed   rc 2 could not grade
set -u
ROOT="$(git -C "$(dirname "$0")" rev-parse --show-toplevel 2>/dev/null)" || exit 2
[ -n "$ROOT" ] || exit 2
cd "$ROOT" || exit 2

VERIFY=wizard-work/volt/q153_verify.py
LANE=wizard-work/beam/CHECK
[ -f "$VERIFY" ] && [ -f "$LANE" ] || {
  echo "CANNOT GRADE: $VERIFY or $LANE is missing"; exit 2; }

legs=0
faults=0
leg() { # leg <name> <rc> <detail>
  legs=$((legs + 1))
  if [ "$2" -eq 0 ]; then printf 'PASS %-12s %s\n' "$1" "$3"
  else printf 'FAIL %-12s %s\n' "$1" "$3"; faults=$((faults + 1)); fi
}

out="$(python3 "$VERIFY" 2>&1)"; rc=$?
leg verify "$rc" "$(printf '%s' "$out" | grep -m1 '^q153:')"
printf '%s\n' "$out" | grep -E '^(PASS|FAIL|UNGRADABLE) ' | sed 's/^/     /'

out="$(bash "$LANE" 2>&1)"; rc=$?
leg lane-check "$rc" "$(printf '%s' "$out" | grep -m1 -E '^(bindings:|CHECK:)' || true)"

if [ "$faults" -eq 0 ]; then
  echo "q153: $legs leg(s), all passed"
  exit 0
fi
echo "q153: $legs leg(s), $faults fault(s)"
exit 1
