#!/usr/bin/env bash
# CHECK-q69-census -- a host-absolute path in this tree is graded by the
# POSITION of the constant that carries it, and the one file in this lane that
# graded the author's checkout now grades the checkout it lives in.
#
# Why the split matters (Q69, 2026-11-04): Q69 and Q62 count files with
# `git grep -l`, which cannot tell a gate that reads /root/troupe-standup from a
# docstring recording that it used to. Measured at this tree: a text scan reads
# 586 of 1345 tracked `wizard-work/**/*.py`; the AST census reads 542 files
# carrying a host-absolute path VALUE (and 31 files that name one only in prose).
# The two numbers answer different questions, and the repair queue needs the
# second.
#
# Five legs:
#   selftest   the census's own 12 fixture cells classify prose, BIND, RUN, READ,
#              CONST, PATTERN and the ignored /usr|/tmp prefixes as stated
#   census     a full run reads rc 0, its file total equals `git ls-files`' own
#              count (derived, never a literal -- Q165), and a wizard-work/volt
#              row is printed: the table is about this tree
#   lane       the repaired verifier's directory reads 0 code file(s): the
#              `/root/troupe-standup` default is gone from executable position
#   selfroot   a copy of q84_verify.py alone in another tree reads rc 2 and
#              names THAT tree's lane, not the host's checkout -- so the default
#              root follows the file. The old default reads rc 0 here.
#   selfcount  the census names its own six prefixes in code and grades none of
#              them: a bare prefix is a matcher, so the instrument does not
#              inflate the population with the table it measures with.
#
# 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)"
CENSUS="$ROOT/wizard-work/volt/q69_hostroot_census.py"
VERIFY="$ROOT/wizard-work/volt/q84-closure/q84_verify.py"
PY="${PYTHON:-python3}"

for f in "$CENSUS" "$VERIFY"; do
    if [ ! -f "$f" ]; then
        printf 'CANNOT GRADE: missing %s\n' "$f"
        exit 2
    fi
done
if ! git -C "$ROOT" rev-parse --show-toplevel >/dev/null 2>&1; then
    printf 'CANNOT GRADE: %s is not a git work tree\n' "$ROOT"
    exit 2
fi

WORK="$(mktemp -d "${TMPDIR:-/tmp}/check-q69.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 census's fixture corpus ------------------------------------
out="$("$PY" "$CENSUS" --selftest 2>&1)"; src=$?
last="$(printf '%s' "$out" | tail -1)"
verdict selftest \
    "$([ "$src" -eq 0 ] && printf '%s' "$last" | grep -q '12 cell(s), 0 failed' && echo 0 || echo 1)" \
    "rc=$src  ${last:-<no output>}"

# --- leg 2: a full reading, counted against the tree's own inventory -------
want="$(git -C "$ROOT" ls-files -z -- wizard-work | tr '\0' '\n' | grep -c '\.py$')"
out="$("$PY" "$CENSUS" --json "$WORK/rows.json" 2>&1)"; crc=$?
n_files="$("$PY" - "$WORK/rows.json" <<'PYEOF' 2>/dev/null
import json, sys
print(json.load(open(sys.argv[1]))["files"])
PYEOF
)"
volt="$("$PY" - "$WORK/rows.json" <<'PYEOF' 2>/dev/null
import json, sys
d = json.load(open(sys.argv[1]))
print(1 if "wizard-work/volt" in d["lanes"] else 0)
PYEOF
)"
ungraded="$(printf '%s' "$out" | grep -c 'UNGRADED')"
verdict census \
    "$([ "$crc" -eq 0 ] && [ "$n_files" = "$want" ] && [ "$volt" -eq 1 ] \
        && [ "$ungraded" -eq 0 ] && echo 0 || echo 1)" \
    "rc=$crc  files=$n_files  git=$want  volt-row=$volt  ungraded=$ungraded"

# --- leg 3: the repaired file's directory has no executing host path -------
out="$("$PY" "$CENSUS" --lane wizard-work/volt/q84-closure 2>&1)"; lrc=$?
last="$(printf '%s' "$out" | grep '^  TOTAL' | tr -s ' ')"
codefiles="$(printf '%s' "$last" | awk '{print $3}')"
verdict lane \
    "$([ "$lrc" -eq 0 ] && [ "${codefiles:-x}" = "0" ] && echo 0 || echo 1)" \
    "rc=$lrc  ${last:-<no TOTAL row>}"

# --- leg 4: the default root follows the file, not the host ----------------
mkdir -p "$WORK/elsewhere/wizard-work/volt/q84-closure" || exit 2
cp "$VERIFY" "$WORK/elsewhere/wizard-work/volt/q84-closure/" || exit 2
out="$("$PY" "$WORK/elsewhere/wizard-work/volt/q84-closure/q84_verify.py" 2>&1)"; vrc=$?
named="$(printf '%s' "$out" | grep -c "$WORK/elsewhere/wizard-work/beam")"
verdict selfroot \
    "$([ "$vrc" -eq 2 ] && [ "$named" -ge 1 ] && echo 0 || echo 1)" \
    "rc=$vrc (want 2)  names-own-lane=$named  $(printf '%s' "$out" | tail -1)"

# --- leg 5: the instrument does not grade its own matcher table ------------
out="$("$PY" "$CENSUS" --lane wizard-work/volt --list --json "$WORK/volt.json" 2>&1)"; mrc=$?
own="$(printf '%s' "$out" | grep -c 'q69_hostroot_census.py')"
pats="$("$PY" - "$WORK/volt.json" <<'PYEOF' 2>/dev/null
import json, sys
print(json.load(open(sys.argv[1]))["pattern_constants"])
PYEOF
)"
verdict selfcount \
    "$([ "$mrc" -eq 0 ] && [ "$own" -eq 0 ] && [ "${pats:-0}" -ge 6 ] && echo 0 || echo 1)" \
    "rc=$mrc  own-rows=$own  patterns=${pats:-x} (>=6)"

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