#!/bin/sh
# Launcher for the Claude Code plugin: runs handoff-verify from the plugin's bundled
# source with any Python >= 3.11 (the package has zero third-party runtime dependencies).
# Hook invocations fail open with exit 1 (non-blocking, stderr visible in Claude Code)
# unless --fail-closed is passed (exit 2).
SCRIPT_PATH="$0"
while [ -L "$SCRIPT_PATH" ]; do
  LINK_TARGET="$(readlink "$SCRIPT_PATH")"
  case "$LINK_TARGET" in
    /*) SCRIPT_PATH="$LINK_TARGET" ;;
    *) SCRIPT_PATH="$(dirname "$SCRIPT_PATH")/$LINK_TARGET" ;;
  esac
done
SCRIPT_ROOT="$(cd "$(dirname "$SCRIPT_PATH")/.." 2>/dev/null && pwd -P)"
if [ -d "$SCRIPT_ROOT/src/handoff_verify" ]; then
  ROOT="$SCRIPT_ROOT"
else
  ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_ROOT}"
fi
PYTHONPATH="$ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
export PYTHONPATH

IS_DARWIN=0
if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
  IS_DARWIN=1
fi

for py in python3 python3.15 python3.14 python3.13 python3.12 python3.11; do
  py_path="$(command -v "$py" 2>/dev/null || true)"
  if [ -z "$py_path" ]; then
    continue
  fi
  # Avoid triggering macOS's Xcode Command Line Tools GUI install dialog on /usr/bin/python3.
  if [ "$IS_DARWIN" = "1" ] && [ "$py_path" = "/usr/bin/python3" ]; then
    if ! xcode-select -p >/dev/null 2>&1; then
      continue
    fi
  fi
  if "$py_path" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' 2>/dev/null; then
    exec "$py_path" -m handoff_verify "$@"
  fi
done

# No suitable python3 on PATH: use one uv already manages, without downloading anything.
if command -v uv >/dev/null 2>&1; then
  py="$(uv python find --no-python-downloads '>=3.11' 2>/dev/null)"
  if [ -n "$py" ] && [ -x "$py" ]; then
    exec "$py" -m handoff_verify "$@"
  fi
fi

echo "handoff-verify: needs Python >= 3.11 (or uv) on PATH" >&2
if [ "$1" = "hook" ]; then
  for arg in "$@"; do
    if [ "$arg" = "--fail-closed" ]; then
      exit 2
    fi
  done
  exit 1
fi
exit 127
