#!/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

stdout_file="$(mktemp)"
stderr_file="$(mktemp)"
cleanup() {
  rm -f "$stdout_file" "$stderr_file"
}
trap cleanup EXIT

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() {
  case "$source_label" in
    cpic)
      [[ "$lower_combined" == *"web_anon"* && "$lower_combined" == *"permission denied"* ]]
      ;;
    nih-reporter)
      [[ "$lower_combined" == *"nih reporter funding data is temporarily unavailable"* ]] || \
        [[ "$lower_combined" == *"nih reporter"* && "$lower_combined" == *"funding"* && "$lower_combined" == *"temporarily unavailable"* ]] || \
        [[ "$lower_combined" == *"nih reporter"* && "$lower_combined" == *"funding"* && "$lower_combined" == *"missing"* && "$lower_combined" == *"table"* ]]
      ;;
  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"
