#!/bin/bash
# CHECK-q137 -- four legs over the work queue's declared open set.
#
#   selftest   13 cells: 8 parser fixtures over synthetic text, then the pin
#              logic itself -- green on the live queue, red on three mutated
#              copies (an appended OPEN record, a DONE turned OPEN, a dropped
#              heading).  A gate that cannot fail is the class this repo keeps
#              filing (Q113, Q120); this leg is what proves it can.
#   open-set   the derived open set and the counts, against their pin.
#   order      line order is commit order (git blame stamps), so "the last
#              record for an id" is "the latest record", not an assumption.
#   closures   one probe per id that was ever opened: is the defect its record
#              describes still present at HEAD?  20 measured, 6 unmeasurable
#              from this tree (network, archive, live gate, database).
#
# Exit codes: 0 all legs green, 1 a leg faulted, 2 a leg could not grade.
set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOOL="$HERE/open_set.py"
PY="${PYTHON:-python3}"
rc=0
legs=0
faults=0

run_leg() {
    name="$1"; shift
    legs=$((legs + 1))
    out="$("$PY" "$TOOL" "$@" 2>&1)"
    lrc=$?
    if [ "$lrc" -eq 0 ]; then
        printf '  %-9s PASS  rc=0  %s\n' "$name" "$(printf '%s' "$out" | tail -1)"
    elif [ "$lrc" -eq 1 ]; then
        faults=$((faults + 1))
        printf '  %-9s FAULT rc=1  %s\n' "$name" "$(printf '%s' "$out" | tail -1)"
        printf '%s\n' "$out" | grep -E '^(FAIL|!)' | head -5
    else
        faults=$((faults + 1))
        printf '  %-9s UNGRADABLE rc=%s  %s\n' "$name" "$lrc" "$(printf '%s' "$out" | tail -1)"
    fi
    [ "$lrc" -eq 0 ] || rc=1
}

run_leg selftest --selftest
run_leg open-set --check
run_leg order --order
run_leg closures --closures

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