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

mode="text"
while (($# > 0)); do
  case "$1" in
    --kv) mode="kv"; shift ;;
    -h | --help)
      echo "Usage: ai/tools/runtime-scorecard/playwright-probe.sh [--kv]"
      exit 0
      ;;
    *) echo "playwright probe error: unknown argument: $1" >&2; exit 2 ;;
  esac
done

run_probe() {
  if command -v yarn >/dev/null 2>&1; then
    if command -v timeout >/dev/null 2>&1; then
      timeout 8s yarn exec playwright --version
    else
      yarn exec playwright --version
    fi
    return
  fi

  if command -v npx >/dev/null 2>&1; then
    if command -v timeout >/dev/null 2>&1; then
      timeout 8s npx --no-install playwright --version
    else
      echo "timeout unavailable; skipping npx Playwright check to avoid blocking" >&2
      return 3
    fi
    return
  fi

  echo "yarn/npx unavailable" >&2
  return 3
}

output=""
status=0
output="$(run_probe 2>&1)" || status=$?
version=""
if (( status == 0 )); then
  version="$output"
fi

if [[ "$mode" == "kv" ]]; then
  if (( status == 0 )); then
    printf 'available=true\n'
  else
    printf 'available=false\n'
  fi
  printf 'version=%q\n' "$version"
  printf 'exit_code=%s\n' "$status"
  printf 'output=%q\n' "$output"
else
  if (( status == 0 )); then
    printf '%s\n' "$version"
  else
    printf 'WARN: Playwright unavailable: %s\n' "$output"
  fi
fi

exit "$status"
