#!/usr/bin/env bash
# CHECK-q167 -- the queue's open-set pin matches the queue it sits beside, in
# this worktree AND in the commit, and the reading is not unconditional.
#
# The defect (Q167, 2026-11-04): `56d3853` appended a heading to
# `WORK-QUEUE.md` (`## Q69 addendum 2 ...`), re-rendered `docs/queue-index.md`
# and left `PIN_COUNTS` in `wizard-work/volt/q137-open-set/open_set.py` at the
# pre-append values, so the repo gate's open-set leg read
# `FAIL count headings moved 116 -> 117` at HEAD and `gate: FAULT` for two
# commits. The append-audit leg stayed green because the index was current:
# nothing graded the pin per commit.
#
# Four legs:
#   pin     this worktree's `open_set.py --check` reads rc 0 and prints
#           `CHECK OK`
#   counts  an independent grep/sort recount of WORK-QUEUE.md -- headings,
#           heading ids, records, record ids -- equals the numbers the tool
#           prints, so the pin is graded against the file, not against itself
#   tree    `git archive HEAD` into a scratch dir, graded by that tree's own
#           open_set.py: the commit is read, not the worktree (this leg reads
#           rc 1 at 56d3853)
#   poison  a copy of the queue with one appended heading must red, so the
#           green above is the pin and not an unconditional pass
#
# Exit codes: 0 all legs passed, 1 a fault, 2 could not grade.
set -u
set -o pipefail

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 2
ROOT="$(pwd)"
QUEUE="$ROOT/WORK-QUEUE.md"
TOOL="$ROOT/wizard-work/volt/q137-open-set/open_set.py"
PY="${PYTHON:-python3}"

for f in "$QUEUE" "$TOOL"; do
    if [ ! -f "$f" ]; then
        printf 'CANNOT GRADE: missing %s\n' "$f"
        exit 2
    fi
done

WORK="$(mktemp -d "${TMPDIR:-/tmp}/check-q167.XXXXXX")" || exit 2
trap 'rm -rf "$WORK"' EXIT

passed=0
failed=0
row() { printf '  %-8s %s\n' "$1" "$2"; }
verdict() { if [ "$2" -eq 0 ]; then passed=$((passed + 1)); else failed=$((failed + 1)); fi; row "$1" "$3"; }

# --- leg 1: the worktree pin is the worktree queue ---------------------------
out="$("$PY" "$TOOL" --repo "$ROOT" --check 2>&1)"; rc=$?
last="$(printf '%s' "$out" | tail -1)"
verdict pin \
    "$([ "$rc" -eq 0 ] && printf '%s' "$out" | grep -q 'CHECK OK' && echo 0 || echo 1)" \
    "rc=$rc  ${last:-<no output>}"

# --- leg 2: the tool's counts are the file's counts --------------------------
heads="$(grep -cE '^##+ +Q[0-9]+' "$QUEUE")"
recs="$(grep -cE '^\*\*Q[0-9]+ +—' "$QUEUE")"
head_ids="$(grep -oE '^##+ +Q[0-9]+' "$QUEUE" | grep -oE 'Q[0-9]+' | sort -u | wc -l | tr -d ' ')"
rec_ids="$(grep -oE '^\*\*Q[0-9]+ +—' "$QUEUE" | grep -oE 'Q[0-9]+' | sort -u | wc -l | tr -d ' ')"
line="$(printf '%s' "$out" | head -1)"
hits=0
printf '%s' "$line" | grep -q "$heads headings/$head_ids ids" && hits=$((hits + 1))
printf '%s' "$line" | grep -q "$recs records/$rec_ids ids" && hits=$((hits + 1))
verdict counts "$([ "$hits" -eq 2 ] && echo 0 || echo 1)" \
    "recount=$heads headings/$head_ids ids, $recs records/$rec_ids ids  hits=$hits/2"

# --- leg 3: the committed tree, graded by its own tool ------------------------
mkdir -p "$WORK/head" || exit 2
if ! git -C "$ROOT" archive HEAD | tar -x -C "$WORK/head" 2>"$WORK/tar.log"; then
    printf 'CANNOT GRADE: git archive HEAD failed: %s\n' "$(tail -1 "$WORK/tar.log")"
    exit 2
fi
tout="$("$PY" "$WORK/head/wizard-work/volt/q137-open-set/open_set.py" \
    --repo "$WORK/head" --check 2>&1)"; trc=$?
rev="$(git -C "$ROOT" rev-parse --short HEAD)"
tlast="$(printf '%s' "$tout" | tail -1)"
verdict tree \
    "$([ "$trc" -eq 0 ] && printf '%s' "$tout" | grep -q 'CHECK OK' && echo 0 || echo 1)" \
    "HEAD=$rev rc=$trc  ${tlast:-<no output>}"

# --- leg 4: one appended heading must red ------------------------------------
mkdir -p "$WORK/poison" || exit 2
cp "$TOOL" "$WORK/poison/open_set.py" || exit 2
cp "$QUEUE" "$WORK/poison/WORK-QUEUE.md" || exit 2
printf '\n## Q999 poison — a heading the pin did not count\n' >> "$WORK/poison/WORK-QUEUE.md"
pout="$("$PY" "$WORK/poison/open_set.py" --repo "$WORK/poison" --check 2>&1)"; prc=$?
named="$(printf '%s' "$pout" | grep -c 'headings')"
plast="$(printf '%s' "$pout" | tail -1)"
verdict poison \
    "$([ "$prc" -eq 1 ] && [ "$named" -ge 1 ] && echo 0 || echo 1)" \
    "rc=$prc (want 1)  headings-named=$named  ${plast:-<no output>}"

if [ "$failed" -eq 0 ]; then
    echo "q167: $passed leg(s), 0 fault(s), rc 0"
    exit 0
fi
echo "q167: $passed passed, $failed fault(s), rc 1"
exit 1
