#!/usr/bin/env bash
# CHECK-q69-ledger-extract -- guard for Q69 addendum 5.
# The ledger-extract pair (generate_ledger_extract.py + check_ledger_extract.py)
# must grade the checkout it lives in, never /root/troupe-standup.
# Legs: text, run, export, derive, teeth. rc 0 = all pass, 1 = fault, 2 = skip.
set -u
REPO="$(cd "$(dirname "$0")/../.." && pwd)"
LEDGER="$REPO/wizard-work/ledger"
GEN="$LEDGER/generate_ledger_extract.py"
CHK="$LEDGER/check_ledger_extract.py"
FAULTS=0
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

leg() { # name, rc
  if [ "$2" -eq 0 ]; then echo "PASS: $1"; else echo "FAULT: $1"; FAULTS=$((FAULTS+1)); fi
}

# text -- no host-absolute literal in either file of the pair
N=$(grep -c "/root/troupe-standup" "$GEN" "$CHK" 2>/dev/null | awk -F: '{s+=$NF} END {print s+0}')
[ "$N" -eq 0 ]; leg "text (host literal count $N, want 0)" $?

# run -- the checker passes in this tree, on this tree's files
python3 "$CHK" > "$TMP/run.log" 2>&1; RC=$?
grep -q "CHECK PASS" "$TMP/run.log" && [ $RC -eq 0 ]; leg "run (rc $RC, $(cat "$TMP/run.log" | head -1))" $?

# export -- the checker passes from a git archive export of HEAD, where no
# /root/troupe-standup exists (ls confirms); the verdict is about the export
if [ -e /root/troupe-standup ]; then echo "SKIP: export (/root/troupe-standup exists on this host)"; else
  mkdir -p "$TMP/export" && git -C "$REPO" archive HEAD -- wizard-work/ledger | tar -x -C "$TMP/export"
  python3 "$TMP/export/wizard-work/ledger/check_ledger_extract.py" > "$TMP/export.log" 2>&1; RC=$?
  grep -q "CHECK PASS" "$TMP/export.log" && [ $RC -eq 0 ]; leg "export (rc $RC, $(head -1 "$TMP/export.log"))" $?
fi

# derive -- the generator, run in the export, rewrites a byte-identical
# extract: it grades the files the caller named, not a host default
if [ -d "$TMP/export" ]; then
  python3 "$TMP/export/wizard-work/ledger/generate_ledger_extract.py" > "$TMP/derive.log" 2>&1; RC=$?
  cmp -s "$TMP/export/wizard-work/ledger/ledger-extract.tsv" "$REPO/wizard-work/ledger/ledger-extract.tsv" && [ $RC -eq 0 ]
  leg "derive (gen rc $RC, extract byte-identical to committed)" $?
fi

# teeth -- the text predicate fires on a copy carrying one literal back,
# and the pre-fix checker blob crashes (FileNotFoundError) where the
# repaired one passes, so the green above is not a guard that cannot fail
cp "$CHK" "$TMP/teeth.py"
sed -i 's|_HERE / "wizardwork-file-manifest.tsv"|"/root/troupe-standup/wizard-work/ledger/wizardwork-file-manifest.tsv"|' "$TMP/teeth.py"
T=$(grep -c "/root/troupe-standup" "$TMP/teeth.py")
[ "$T" -eq 1 ]; leg "teeth (predicate fires on 1 restored literal)" $?

if [ $FAULTS -eq 0 ]; then echo "CHECK-q69-ledger-extract: 5 leg(s), 0 fault(s)"; exit 0
else echo "CHECK-q69-ledger-extract: $FAULTS fault(s)"; exit 1; fi
