#!/usr/bin/env bash
# ghc — the ONLY command arm A may use to read from GitHub.
#
# Runs a read-only `gh` command, pipes its stdout through Headroom, prints the
# compressed output, and appends one measured record to $GHC_LOG (JSONL) so the
# "chars in" score comes from instrumentation, never from the model's self-report.
# The compressor also stores raw/compressed artifacts and the exact Headroom
# transform decision, so ratio=0 can be classified instead of guessed.
#
# Usage:   ghc <gh-args...>
# Example: ghh api repos/pallets/flask/git/trees/main?recursive=1
#          ghc search code --repo facebook/react useState --limit 20
#          ghc issue list --repo cli/cli --state all --limit 30 --json number,title,labels
#
# Setup (once):
#   export HR_PY="$HOME/.local/share/uv/tools/headroom-ai/bin/python"
#   export GHC_LOG="$PWD/tmp/run.jsonl"       # where measurements accumulate (tmp/ is gitignored)
#   export PATH="$(dirname "$0"):$PATH"       # so `ghc` is on PATH
set -euo pipefail

HR_PY="${HR_PY:-$HOME/.local/share/uv/tools/headroom-ai/bin/python}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Default log lives under the gitignored tmp/; create its dir so appends never fail.
GHC_LOG="${GHC_LOG:-$PWD/tmp/run.jsonl}"
GHC_ARTIFACT_DIR="${GHC_ARTIFACT_DIR:-${GHC_LOG%.jsonl}-artifacts}"
GHC_DIAGNOSTICS_LOG="${GHC_DIAGNOSTICS_LOG:-${GHC_LOG%.jsonl}-diagnostics.log}"
mkdir -p "$(dirname "$GHC_LOG")"
mkdir -p "$GHC_ARTIFACT_DIR"

# --- read-only guard: reject any mutating gh verb -------------------------------
case "${1:-}" in
  api)
    # allow only GET (no -X/--method other than GET) on api
    for a in "$@"; do
      case "$a" in
        -X|--method) echo "ghc: only GET api calls are allowed in arm A" >&2; exit 2;;
      esac
    done
    ;;
  search|repo|pr|issue|browse|status) : ;;  # read-only families
  *) echo "ghc: '$1' is not an allowed read-only gh family" >&2; exit 2;;
esac
# forbid known mutation subverbs
case "${2:-}" in
  create|edit|delete|close|reopen|merge|comment|review|lock|unlock|transfer|rename|clone|fork|sync|ready|checkout)
    echo "ghc: mutating subcommand '$2' is not allowed in arm A" >&2; exit 2;;
esac

# Capture successful and failed probes alike. A failed query is workflow waste,
# not invisible work: its complete output is compressed, logged, and returned
# with the original gh exit status so the runner can correct it.
set +e
raw="$(gh "$@" 2>&1)"
gh_status=$?
set -e
command_label="gh $(printf '%s ' "$@" | sed 's/ *$//')"

# Compress; capture the measurement line from stderr.
tmp_err="$(mktemp)"
compressed="$(printf '%s' "$raw" | \
  HR_LOG="$GHC_LOG" \
  HR_ARTIFACT_DIR="$GHC_ARTIFACT_DIR" \
  HR_COMMAND="$command_label" \
  HR_SOURCE_EXIT_CODE="$gh_status" \
  "$HR_PY" "$HERE/hr_compress.py" 2>"$tmp_err")"

# Preserve warnings (including model-readiness failures) and the measurement
# record. The JSONL remains the machine-readable source for scoring.
if [[ -s "$tmp_err" ]]; then
  {
    printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$command_label"
    sed '/^HEADROOM_MEASUREMENT=/d' "$tmp_err"
  } >> "$GHC_DIAGNOSTICS_LOG"
fi
rm -f "$tmp_err"

printf '%s' "$compressed"
exit "$gh_status"
