#!/usr/bin/env bash
set -euo pipefail

usage() {
  echo "usage: tools/biomcp-verify-live <cpic|nih-reporter> -- <command> [args...]" >&2
}

if [[ $# -lt 3 || "${2:-}" != "--" ]]; then
  usage
  exit 2
fi

source_label="$1"
shift 2

case "$source_label" in
  cpic|nih-reporter) ;;
  *)
    usage
    exit 2
    ;;
esac

work_dir="$(mktemp -d)"
chmod 700 "$work_dir"
stdout_file="$work_dir/stdout"
stderr_file="$work_dir/stderr"
pending_sentinel="$work_dir/nih-reporter.pending"
pending_marker="biomcp-nih-reporter-unavailable-v1"
cleanup() {
  rm -f "$stdout_file" "$stderr_file" "$pending_sentinel"
  rmdir "$work_dir" 2>/dev/null || true
}
trap cleanup EXIT

unset BIOMCP_VERIFY_LIVE_PENDING_SENTINEL
if [[ "$source_label" == "nih-reporter" ]]; then
  export BIOMCP_VERIFY_LIVE_PENDING_SENTINEL="$pending_sentinel"
fi

set +e
"$@" >"$stdout_file" 2>"$stderr_file"
status=$?
set -e

cat "$stdout_file"
cat "$stderr_file" >&2

if [[ $status -eq 0 ]]; then
  exit 0
fi

combined="$(cat "$stdout_file" "$stderr_file")"
lower_combined="${combined,,}"

is_hard_failure() {
  [[ "$lower_combined" == *"thread '"*"panicked"* ]] || \
    [[ "$lower_combined" == *"backtrace"* ]] || \
    [[ "$lower_combined" == *"json parse"* ]] || \
    [[ "$lower_combined" == *"invalid json"* ]]
}

is_operator_pending() {
  local sentinel_value sentinel_size
  case "$source_label" in
    cpic)
      [[ "$lower_combined" == *"web_anon"* && "$lower_combined" == *"permission denied"* ]]
      ;;
    nih-reporter)
      [[ -f "$pending_sentinel" && ! -L "$pending_sentinel" ]] || return 1
      IFS= read -r sentinel_value < "$pending_sentinel" || return 1
      sentinel_size="$(wc -c < "$pending_sentinel")"
      [[ "$sentinel_value" == "$pending_marker" ]] &&
        [[ "$sentinel_size" -eq $((${#pending_marker} + 1)) ]]
      ;;
  esac
}

if ! is_hard_failure && is_operator_pending; then
  printf 'operator-pending: %s live source unavailable/auth-pending; product-owned deterministic contracts remain the routine proof.\n' "$source_label" >&2
  exit 0
fi

printf 'product-red: %s live check failed with unclassified status %s.\n' "$source_label" "$status" >&2
exit "$status"
