#!/bin/sh
# Claude Code plugin hook launcher.
# Fail-open: when no usable Python engine exists, say why on stderr once and
# emit an empty hook response (exit 0) so the host session continues untouched.
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." 2>/dev/null && pwd) || { printf '{}\n'; exit 0; }

# >>> resolve-python >>>
# Shared by bin/tokensafe-mcp and bin/tokensafe-claude-hook; both copies must
# stay byte-identical (tests/test_plugin_launchers.py fails on drift).
#
# Sets PY to the interpreter bin/tokensafe.js provisions, in this order:
#   1. TOKENSAFE_PYTHON           explicit pin, used as-is (no fallback)
#   2. $TOKENSAFE_HOME/venv       default ~/.tokensafe/venv
#   3. $TOKENSAFE_HOME/runtime/*  newest complete managed CPython
#   4. python3 / python on PATH   only when it runs CPython 3.10+
# GUI-launched agents on macOS inherit a PATH whose python3 is often the 3.9
# Xcode stub, which is why PATH comes last and is version-checked. Nothing is
# imported beyond `sys`: hooks start on every tool call, so no cryptography
# probe here (the engine reports a missing dependency itself).
ts_is_uint() {
  case "$1" in ''|*[!0-9]*) return 1 ;; esac
  return 0
}

# Succeeds when "X.Y[.Z...]" names Python >= 3.10.
ts_version_ok() {
  ts_major=${1%%.*}
  ts_rest=${1#*.}
  ts_minor=${ts_rest%%.*}
  ts_is_uint "$ts_major" && ts_is_uint "$ts_minor" || return 1
  [ "$ts_major" -gt 3 ] || { [ "$ts_major" -eq 3 ] && [ "$ts_minor" -ge 10 ]; }
}

# A venv records its base version in pyvenv.cfg: reading it costs no process.
# An unreadable or unparseable file is accepted (the venv was made by an
# installer that already required 3.10+).
ts_venv_ok() {
  [ -f "$1/pyvenv.cfg" ] || return 0
  while IFS= read -r ts_line || [ -n "$ts_line" ]; do
    case "$ts_line" in
      version[\ =]*|version_info[\ =]*)
        ts_v=${ts_line#*=}
        ts_v=${ts_v# }
        ts_version_ok "$ts_v"
        return
        ;;
    esac
  done < "$1/pyvenv.cfg"
  return 0
}

# Succeeds when runtime dir name $1 ("3.12.8-20250106") is newer than $2.
ts_runtime_newer() {
  [ -n "$2" ] || return 0
  ts_a=$1; ts_b=$2
  for ts_i in 1 2 3 4; do
    ts_na=${ts_a%%[.-]*}; ts_nb=${ts_b%%[.-]*}
    ts_is_uint "$ts_na" || ts_na=0
    ts_is_uint "$ts_nb" || ts_nb=0
    [ "$ts_na" -gt "$ts_nb" ] && return 0
    [ "$ts_na" -lt "$ts_nb" ] && return 1
    case "$ts_a" in *[.-]*) ts_a=${ts_a#*[.-]} ;; *) ts_a=0 ;; esac
    case "$ts_b" in *[.-]*) ts_b=${ts_b#*[.-]} ;; *) ts_b=0 ;; esac
  done
  return 1
}

ts_find_python() {
  PY=""
  ts_home=${TOKENSAFE_HOME:-$HOME/.tokensafe}

  if [ -n "${TOKENSAFE_PYTHON:-}" ]; then
    if command -v "$TOKENSAFE_PYTHON" >/dev/null 2>&1; then
      PY=$TOKENSAFE_PYTHON
      return 0
    fi
    TS_WHY="TOKENSAFE_PYTHON=$TOKENSAFE_PYTHON is not an executable"
    return 1
  fi

  if [ -x "$ts_home/venv/bin/python3" ] && ts_venv_ok "$ts_home/venv"; then
    PY=$ts_home/venv/bin/python3
    return 0
  fi

  ts_best=""; ts_best_name=""
  for ts_dir in "$ts_home"/runtime/*; do
    [ -f "$ts_dir/.complete" ] || continue
    for ts_exe in "$ts_dir/python/bin/python3" "$ts_dir/bin/python3"; do
      [ -x "$ts_exe" ] || continue
      ts_name=${ts_dir##*/}
      if ts_runtime_newer "$ts_name" "$ts_best_name"; then
        ts_best=$ts_exe; ts_best_name=$ts_name
      fi
      break
    done
  done
  if [ -n "$ts_best" ]; then
    PY=$ts_best
    return 0
  fi

  for ts_cand in python3 python; do
    ts_path=$(command -v "$ts_cand" 2>/dev/null) || continue
    case "$ts_path" in *[Ww]indows[Aa]pps*) continue ;; esac
    if "$ts_path" -I -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' >/dev/null 2>&1; then
      PY=$ts_path
      return 0
    fi
  done

  TS_WHY="no Python 3.10+ found (checked TOKENSAFE_PYTHON, $ts_home/venv, $ts_home/runtime, python3/python on PATH)"
  return 1
}

TS_FIX="run 'npx -y tokensafe doctor' (or 'tokensafe doctor') once to provision the pinned runtime, or set TOKENSAFE_PYTHON=/path/to/python3"
# <<< resolve-python <<<

if ! ts_find_python; then
  echo "tokensafe: $TS_WHY; $TS_FIX" >&2
  printf '{}\n'
  exit 0
fi
exec "$PY" "$ROOT/hooks/claude_code_hook.py"
