#!/usr/bin/env bash
# Q62 forge lane, 2026-11-05 -- the 12 chunker probes must import the module this
# repository tracks, not a copy on the host.
#
# The defect this guards: every one of these files opened with
#     sys.path.insert(0, "<host>/wizard-work-outputs/forge")
# and then `import chunker`.  The tree tracks `wizard-work/forge/chunker.py`
# beside them (300 lines, sha256 c9389d28e9fe...), the host held a different file
# (311 lines, sha256 6df7fd7a6dd2...), and `tools/import_resolve_check.py` classes
# these names (`_fuzz_probe.py`, `_repro_bounds.py`, ...) as ADVISORY, so the repo
# gate read green over all twelve.  On a checkout without the host directory they
# die on `ModuleNotFoundError: No module named 'chunker'`.
#
# Legs:
#   bind    no host-absolute insert is left in any `wizard-work/forge/*.py`
#   assert  each of the 12 carries the binding assertion
#   run     each of the 12 runs rc 0 in a copy that holds ONLY the tree's files
#   teeth   the `bind` predicate fires on a copy with the host insert restored
#   census  the Q62 census reads 7 live-unstated positions in this lane, not 19
#
# rc 0 every leg as expected / rc 1 a graded fault / rc 2 could not grade.
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
FORGE="$ROOT/wizard-work/forge"
CENSUS="$HERE/q62_lane_census.py"
HOST_INSERT='sys.path.insert(0, "/root/.hermes/wizard-outputs/forge")'
TREE_INSERT='sys.path.insert(0, str(Path(__file__).resolve().parent))'
ASSERT='assert Path(chunker.__file__).resolve().parent == Path(__file__).resolve().parent, chunker.__file__'
WANT=12

legs=0; faults=0
fault() { legs=$((legs+1)); faults=$((faults+1)); echo "FAIL: $1 -- $2"; }
pass()  { legs=$((legs+1)); echo "PASS $1: $2"; }

[ -d "$FORGE" ] || { echo "FAIL: could not grade -- no $FORGE" >&2; exit 2; }
[ -f "$CENSUS" ] || { echo "FAIL: could not grade -- no $CENSUS" >&2; exit 2; }

# ---- bind ------------------------------------------------------------------
hits="$(grep -rl --include='*.py' -F "$HOST_INSERT" "$FORGE" 2>/dev/null | wc -l)"
if [ "$hits" -eq 0 ]; then
    pass bind "0 file(s) under wizard-work/forge bind a host-absolute insert"
else
    fault bind "$hits file(s) still bind the host directory: $(grep -rl --include='*.py' -F "$HOST_INSERT" "$FORGE" | sed "s|$ROOT/||" | tr '\n' ' ')"
fi

# ---- the 12, discovered rather than listed ---------------------------------
bound="$(grep -rl --include='*.py' -F "$TREE_INSERT" "$FORGE" 2>/dev/null | sort)"
n_bound="$(printf '%s\n' "$bound" | grep -c . )"
roster_ok=1
if [ "$n_bound" -ne "$WANT" ]; then
    fault roster "$n_bound file(s) bind beside themselves, expected $WANT"
    roster_ok=0
else
    pass roster "$n_bound file(s) bind beside themselves, as expected"
fi

# A leg that has nothing to grade says SKIP and is neither a pass nor a fault --
# the roster leg already carries the verdict for an empty or over-full set.
skip() { echo "SKIP $1: $2"; }

# ---- assert ----------------------------------------------------------------
if [ "$roster_ok" -eq 0 ]; then
    skip assert "roster is $n_bound/$WANT, nothing to assert against"
else
    missing=""
    while IFS= read -r f; do
        [ -n "$f" ] || continue
        grep -qF "$ASSERT" "$f" || missing="$missing $(basename "$f")"
    done <<< "$bound"
    if [ -z "$missing" ]; then
        pass assert "all $n_bound repaired file(s) assert the module landed beside them"
    else
        fault assert "binding assertion missing in:$missing"
    fi
fi

# ---- run: a copy holding ONLY the tree's files ------------------------------
sb="$(mktemp -d "${TMPDIR:-/tmp}/q62-forge-XXXXXX")" || { echo "FAIL: could not grade -- no temp dir" >&2; exit 2; }
trap 'rm -rf "$sb"' EXIT
cp "$FORGE"/*.py "$sb"/ 2>/dev/null
[ -d "$FORGE/refactored_cards" ] && cp -r "$FORGE/refactored_cards" "$sb"/ 2>/dev/null
if [ "$roster_ok" -eq 0 ]; then
    skip run "roster is $n_bound/$WANT, nothing to run"
else
    run_bad=""
    while IFS= read -r f; do
        [ -n "$f" ] || continue
        name="$(basename "$f")"
        if ! out="$(cd "$sb" && timeout 300 python3 "$sb/$name" 2>&1)"; then
            run_bad="$run_bad $name(rc!=0:$(printf '%s' "$out" | tail -1))"
        fi
    done <<< "$bound"
    if [ -z "$run_bad" ]; then
        pass run "$n_bound file(s) run rc 0 from a copy with no host directory"
    else
        fault run "did not run clean:$run_bad"
    fi
fi

# ---- teeth -----------------------------------------------------------------
first="$(printf '%s\n' "$bound" | head -1)"
if [ -z "$first" ]; then
    skip teeth "no repaired file to mutate (roster leg carries the verdict)"
else
    teeth_dir="$sb/teeth"
    mkdir -p "$teeth_dir"
    sed "s|^$TREE_INSERT\$|$HOST_INSERT|" "$first" > "$teeth_dir/$(basename "$first")"
    if grep -qF "$HOST_INSERT" "$teeth_dir/$(basename "$first")"; then
        pass teeth "the bind predicate fires on a copy with the host insert restored ($(basename "$first"))"
    else
        fault teeth "the mutation did not restore the host insert -- the teeth leg proves nothing"
    fi
fi

# ---- census ----------------------------------------------------------------
cout="$(cd "$ROOT" && python3 "$CENSUS" --repo . --lane forge 2>&1)"
crc=$?
if [ "$crc" -eq 2 ]; then
    echo "FAIL: could not grade -- census rc 2: $(printf '%s' "$cout" | tail -1)" >&2
    exit 2
fi
line="$(printf '%s\n' "$cout" | grep -E '^forge ' | head -1)"
if [ -z "$line" ]; then
    echo "FAIL: could not grade -- census printed no forge row" >&2
    exit 2
fi
n_live="$(printf '%s' "$line" | sed -n 's/.*live-unstated= *\([0-9][0-9]*\).*/\1/p')"
if [ "$n_live" = "7" ]; then
    pass census "forge lane reads 7 live-unstated position(s), the 12 bindings are gone"
else
    fault census "forge lane reads ${n_live:-?} live-unstated position(s), expected 7"
fi

echo "q62-forge: $legs leg(s), $faults fault(s)"
[ "$faults" -eq 0 ] && exit 0
exit 1
