#!/usr/bin/env bash
# CHECK-q159 -- the sweep's path census is complete, and the one red entry point
# it found was repaired rather than signed away (volt, 2026-11-02; the census and
# register legs were re-scoped 2026-11-03 by Q167, see the header of each).
#
# What this guards:
#   1. census     the path census names NO fault for any of the 21 paths this
#                 item signed, and does not name CHECK-q159 itself as missing or
#                 unreviewed. Faults on other lanes' new entry points are printed
#                 as context and NOT graded here: that repo-wide tooth is
#                 CHECK-q143's, and a leg that reds when a neighbour signs a row
#                 cannot be re-run, which is why this one was red on arrival.
#   2. coverage   the beam lane's coverage tool reads 0 faults -- the leg that was
#                 red because tarjan_scc.py had no collected cell.
#   3. cells      test_tarjan_scc.py is collected and its 8 cells pass.
#   4. mutant     the same 8 cells FAIL against a copy of tarjan_scc.py with the
#                 parent lowlink propagation dropped. A cell that cannot red is
#                 not evidence; this leg is why the test is worth its name.
#   5. register   the Q159 block in check_entry_baseline.tsv reads as 21 rows, of
#                 which exactly 2 carry a non-zero code and both are the KNOWN RED
#                 rows this tick signed. The block has a boundary now: the awk
#                 this replaced counted from its marker to EOF and read 27, so it
#                 graded six later sections of other lanes' rows.
#   6. scope      block_rows.py's own selftest passes, including the cell that
#                 shows a marker-to-EOF reading of the same fixture disagrees with
#                 the block reading -- so the boundary is a measured difference and
#                 not a claim in a comment. No cell count is pinned: a fixture
#                 added later must not redden this leg (the Q158 defect).
#
# Exit codes (tools/ contract): 0 every leg passed, 1 a fault, 2 could not grade.
set -u
set -o pipefail

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 2
ROOT="$(pwd)"
SWEEP="$ROOT/wizard-work/volt/q143-check-sweep/check_sweep.py"
BLOCK="$ROOT/wizard-work/volt/q143-check-sweep/block_rows.py"
BASE="$ROOT/wizard-work/volt/q143-check-sweep/check_entry_baseline.tsv"
MARK='rows added by hand (Q159'
BEAM="$ROOT/wizard-work/beam"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/check-q159.XXXXXX")" || exit 2
trap 'rm -rf "$WORK"' EXIT

pass=0
fail=0
ung=0
row() { printf '  %-12s %s\n' "$1" "$2"; }

for f in "$SWEEP" "$BLOCK" "$BASE" "$BEAM/tarjan_scc.py" \
         "$BEAM/test_tarjan_scc.py" "$BEAM/check_coverage.py"; do
    if [ ! -f "$f" ]; then
        echo "CHECK-q159: no $f -- cannot grade" >&2
        exit 2
    fi
done

# The 21 paths this item signed, read through the block boundary.
if ! python3 "$BLOCK" --file "$BASE" --marker "$MARK" --paths \
        | LC_ALL=C sort >"$WORK/block.paths"; then
    echo "CHECK-q159: cannot read the Q159 block -- cannot grade" >&2
    exit 2
fi
nblock="$(wc -l <"$WORK/block.paths" | tr -d ' ')"

# --- 1: the path census, scoped to this item's own rows -----------------------
python3 "$SWEEP" --repo "$ROOT" --paths >"$WORK/paths.out" 2>&1
p=$?
total="$(tail -n 1 "$WORK/paths.out")"
awk '/^FAIL:/ { print $3 }' "$WORK/paths.out" | LC_ALL=C sort -u >"$WORK/fault.paths"
own="$(LC_ALL=C comm -12 "$WORK/fault.paths" "$WORK/block.paths" | tr '\n' ' ')"
foreign="$(LC_ALL=C comm -23 "$WORK/fault.paths" "$WORK/block.paths" | tr '\n' ' ')"
selfault="$(awk '$1 == "FAIL:" && $3 == "CHECK-q159" { n++ } END { print n + 0 }' \
    "$WORK/paths.out")"
if [ "$p" -eq 2 ]; then
    row census "UNG  the path census could not grade this tree :: $total"
    ung=$((ung + 1))
elif [ -n "$own" ] || [ "$selfault" -ne 0 ] || [ "$nblock" -ne 21 ]; then
    row census "FAULT block=$nblock rows, faulted: ${own:-none}; CHECK-q159 named: $selfault :: $total"
    fail=$((fail + 1))
else
    nforeign="$(printf '%s' "$foreign" | wc -w | tr -d ' ')"
    row census "PASS  none of the 21 signed paths is faulted :: $total"
    row context "$nforeign repo-wide fault(s) on other lanes' rows, ungraded here"
    pass=$((pass + 1))
fi

# --- 2: the coverage leg the repair was for ----------------------------------
python3 "$BEAM/check_coverage.py" >"$WORK/cov.out" 2>&1
p=$?
if [ "$p" -eq 0 ] && grep -q '^coverage: PASS' "$WORK/cov.out"; then
    row coverage "PASS  $(grep '^coverage: [0-9]' "$WORK/cov.out" | tail -n 1)"
    pass=$((pass + 1))
elif [ "$p" -eq 2 ]; then
    row coverage "UNG  rc=2 :: $(grep '^coverage' "$WORK/cov.out" | tail -n 1)"
    ung=$((ung + 1))
else
    row coverage "FAULT rc=$p :: $(grep '^coverage' "$WORK/cov.out" | tail -n 1)"
    fail=$((fail + 1))
fi

# --- 3: the collected cells --------------------------------------------------
( cd "$BEAM" && python3 -m unittest test_tarjan_scc >"$WORK/cells.out" 2>&1 )
p=$?
if [ "$p" -eq 0 ] && grep -q '^Ran 8 tests' "$WORK/cells.out"; then
    row cells "PASS  $(grep '^Ran ' "$WORK/cells.out") $(tail -n 1 "$WORK/cells.out")"
    pass=$((pass + 1))
elif [ "$p" -eq 2 ]; then
    row cells "UNG  rc=2 (the suite could not be collected)"
    ung=$((ung + 1))
else
    row cells "FAULT rc=$p (want 0, 8 cells)"
    tail -n 5 "$WORK/cells.out"
    fail=$((fail + 1))
fi

# --- 4: sensitivity, on a mutated copy ---------------------------------------
mkdir -p "$WORK/mut" && cp "$BEAM/tarjan_scc.py" "$BEAM/test_tarjan_scc.py" "$WORK/mut/" || exit 2
before="$(grep -c 'if lowlink\[u\] < lowlink\[parent\]:' "$WORK/mut/tarjan_scc.py")"
if [ "$before" -ne 1 ]; then
    row mutant "FAULT mutation site matched $before line(s), want 1"
    fail=$((fail + 1))
else
    sed -i 's/if lowlink\[u\] < lowlink\[parent\]:/if False and lowlink[u] < lowlink[parent]:/' \
        "$WORK/mut/tarjan_scc.py"
    ( cd "$WORK/mut" && python3 -m unittest test_tarjan_scc >"$WORK/mut.out" 2>&1 )
    p=$?
    if [ "$p" -eq 1 ] && grep -q '^FAILED (failures=' "$WORK/mut.out"; then
        row mutant "PASS  rc=1, $(tail -n 1 "$WORK/mut.out") on the dropped-lowlink copy"
        pass=$((pass + 1))
    elif [ "$p" -eq 2 ]; then
        row mutant "UNG  rc=2 (the mutated copy did not run)"
        ung=$((ung + 1))
    else
        row mutant "FAULT rc=$p (want 1) -- the cells did not notice the mutation"
        tail -n 5 "$WORK/mut.out"
        fail=$((fail + 1))
    fi
fi

# --- 5: the signed register, read through the block boundary ------------------
summary="$(python3 "$BLOCK" --file "$BASE" --marker "$MARK" 2>"$WORK/reg.err")"
p=$?
if [ "$p" -ne 0 ]; then
    row register "FAULT rc=$p reading the block: $(tail -n 1 "$WORK/reg.err")"
    fail=$((fail + 1))
else
    names="$(python3 "$BLOCK" --file "$BASE" --marker "$MARK" --red \
        | LC_ALL=C sort | tr '\n' ' ')"
    want="CHECK-sol-profile-triage-2026-11-02 wizard-work/ledger/CHECK-wizardwork-census "
    if [ "$summary" = "rows=21 red=2" ] && [ "$names" = "$want" ]; then
        row register "PASS  21 rows, 2 known red: $names"
        pass=$((pass + 1))
    else
        row register "FAULT $summary, red names: ${names:-none}"
        fail=$((fail + 1))
    fi
fi

# --- 6: the boundary's own selftest ------------------------------------------
python3 "$BLOCK" --selftest >"$WORK/scope.out" 2>&1
p=$?
if [ "$p" -eq 0 ] \
   && grep -qE 'selftest: [1-9][0-9]* cell\(s\), 0 failed, 0 skipped' "$WORK/scope.out"; then
    row scope "PASS  $(tail -n 1 "$WORK/scope.out")"
    pass=$((pass + 1))
else
    row scope "FAULT rc=$p (want 0) on the block reader's selftest"
    tail -n 8 "$WORK/scope.out"
    fail=$((fail + 1))
fi

echo
if [ "$ung" -gt 0 ]; then
    echo "q159: $pass passed, $fail fault(s), $ung ungradable"
    exit 2
elif [ "$fail" -gt 0 ]; then
    echo "q159: $pass passed, $fail fault(s)"
    exit 1
fi
echo "q159: 6 leg(s), all passed"
exit 0
