#!/usr/bin/env bash
# observability: what CI/builds run where (GH runners+jobs, buildbox offload, laptop)
set -uo pipefail
REPO="${BB_REPO:-alexcodeplace/multideal}"
REGISTRY_LIB="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../lib/buildbox-registry.mjs"
# BB_BOX names a registry host; it is resolved through the registry like any other,
# so it cannot address a host the registry says must not be contacted.
BOX=""
BOX_NAME="${BB_BOX:-}"
BOX_PORT=22
BOX_KEY=""
if [ -n "$BOX_NAME" ]; then
  BOX_NAME="$(CPU_GUARD_ACTIVE=1 node "$REGISTRY_LIB" check "$BOX_NAME")" || BOX_NAME=""
else
  BOX_NAME="$(CPU_GUARD_ACTIVE=1 node "$REGISTRY_LIB" hosts --order build | cut -d, -f1)" || BOX_NAME=""
fi
if [ -n "$BOX_NAME" ]; then
  read -r BOX BOX_PORT BOX_KEY < <(CPU_GUARD_ACTIVE=1 node "$REGISTRY_LIB" access "$BOX_NAME" --path tailscale_ip) || BOX=""
fi

echo "== GH runners ($REPO) =="
gh api "repos/$REPO/actions/runners" --jq '.runners[] | "\(.name)\t\(.status)\tbusy=\(.busy)"' 2>/dev/null || echo "gh unavailable"
echo "queued runs: $(gh api "repos/$REPO/actions/runs?status=queued&per_page=50" --jq '.workflow_runs | length' 2>/dev/null || echo '?')"

echo
echo "== recent GH jobs (last 5 runs) =="
for id in $(gh api "repos/$REPO/actions/runs?per_page=5" --jq '.workflow_runs[].id' 2>/dev/null); do
  gh api "repos/$REPO/actions/runs/$id/jobs?per_page=20" \
    --jq '.jobs[] | "\(.started_at // "queued")\t\(.status)/\(.conclusion // "-")\trunner=\(.runner_name // "-")\t\(.name)"' 2>/dev/null
done

echo
echo "== ${BOX_NAME:-buildbox} offload jobs (rb-*) =="
if [ -z "$BOX" ]; then
  echo "no reachable buildbox in the registry"
else
  SSH_ID=()
  [ "$BOX_KEY" = "-" ] || [ -z "$BOX_KEY" ] || SSH_ID=(-i "${BOX_KEY/#\~/$HOME}")
  ssh -o BatchMode=yes -o ConnectTimeout=4 -p "$BOX_PORT" "${SSH_ID[@]}" "$BOX" \
    'systemctl --user list-units "rb-*.service" --state=running --no-legend --plain 2>/dev/null || true; uptime' 2>/dev/null \
    || echo "${BOX_NAME:-buildbox} unreachable"
fi

echo
echo "== laptop =="
echo "multideal-runner.service: $(systemctl --user is-active multideal-runner.service 2>/dev/null || true) (fallback-managed, ${BOX_NAME:-the buildbox} is primary)"
echo "platform runner: $(systemctl is-active actions.runner.platform-modules-mod.platform-devbox.service 2>/dev/null || true)"
keys=$(ls "$HOME/.claude/run/local-gate/"*.key 2>/dev/null | xargs -rn1 basename | tr '\n' ' ')
echo "local-gate active keys: ${keys:-none}"
echo "-- offload log (last 5) --"
tail -5 "$HOME/.claude/local-gate.log" 2>/dev/null || echo none
echo "-- ci-fallback log (last 5) --"
tail -5 "$HOME/.claude/ci-fallback.log" 2>/dev/null || echo none
