#!/bin/sh
# Launcher for the Claude Code plugin: runs compact-ledger from the plugin's bundled
# source with any Python >= 3.11 (the package has no third-party dependencies).
# Hook invocations always exit 0 so a missing interpreter never interrupts a session.
ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
PYTHONPATH="$ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
export PYTHONPATH

for py in python3 python3.15 python3.14 python3.13 python3.12 python3.11; do
  if command -v "$py" >/dev/null 2>&1 &&
    "$py" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' 2>/dev/null; then
    exec "$py" -m compact_ledger "$@"
  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 compact_ledger "$@"
  fi
fi

# Hook invocations fail open unless --strict was explicitly requested.
is_hook=0
is_strict=0
prev=""
for arg in "$@"; do
  if [ "$arg" = "--strict" ]; then
    is_strict=1
  elif [ "$prev" = "--store-dir" ]; then
    prev=""
    continue
  elif [ "$arg" = "--store-dir" ]; then
    prev="--store-dir"
    continue
  elif [ "$is_hook" = "0" ]; then
    case "$arg" in
      -*) ;;
      hook) is_hook=1 ;;
      *) break ;;
    esac
  fi
done
if [ "$is_hook" = "1" ] && [ "$is_strict" = "0" ]; then
  exit 0
fi
echo "compact-ledger: needs Python >= 3.11 (or uv) on PATH" >&2
exit 127
