#!/usr/bin/env bash
# Resolve the `svg-mcp` CLI, fetching it if absent, and run it with these arguments.
#   1. uv run --project $SVG_MCP_DEV, for a checkout (SVG_MCP_DEV=1: this repo's own)
#   2. uvx svg-mcp@$SVG_MCP_VERSION, an explicit release, used as given
#   3. PATH (skipping ourselves), when at least this plugin's version
#   4. uvx svg-mcp@<this plugin's version>
#   5. uvx svg-mcp (the latest), if that pinned release can't be fetched
# The same order as the Pi and OpenCode plugins (and cribsheet's bin/crib and
# mcp-combiner's): overrides first, then an installed binary only if new enough, then
# the pin.
#
# Used by BOTH the SessionStart hook (to serve the MCP backend, through sharedserver,
# so the choice is made only when the server actually starts) and /svg-mcp:skill
# (`svg-mcp skills ...`), so the CLI and the server never disagree about which svg-mcp
# they mean.
#
# This pins to the plugin's own version: the plugin ships svg-mcp, so the two move in
# lockstep and the floor IS the pin.

set -eu

_plugin_root="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"

_plugin_version() {
  local pj="$_plugin_root/.claude-plugin/plugin.json"
  [ -f "$pj" ] || return 1
  if command -v jq >/dev/null 2>&1; then
    jq -r '.version // empty' <"$pj"
  else
    sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$pj" | head -1
  fi
}

_version_ge() {
  local a b i x y
  local IFS=.
  read -r -a a <<<"${1%%[!0-9.]*}"
  read -r -a b <<<"${2%%[!0-9.]*}"
  for i in 0 1 2; do
    x="${a[i]:-0}"; y="${b[i]:-0}"
    ((10#${x:-0} > 10#${y:-0})) && return 0
    ((10#${x:-0} < 10#${y:-0})) && return 1
  done
  return 0
}

_ver="$(_plugin_version || true)"

# SVG_MCP_LAUNCHER_PROBE=1: print which route this launcher would take
# (checkout, version, path, pinned, latest; none when nothing can run) and exit,
# instead of running svg-mcp.
# The SessionStart hook asks this so it can warn when the pinned release can't be
# fetched, without duplicating these rules.
_run() { # _run <route> <command...>
  local route="$1"; shift
  if [ -n "${SVG_MCP_LAUNCHER_PROBE:-}" ]; then echo "$route"; exit 0; fi
  exec "$@"
}

# A checkout, when explicitly pointed at one. SVG_MCP_DEV=1 means the repo this plugin
# sits in (a clone, not a marketplace install, which has no source).
if [ -n "${SVG_MCP_DEV:-}" ] && command -v uv >/dev/null 2>&1; then
  _project="$SVG_MCP_DEV"
  [ "$_project" = 1 ] && _project="$_plugin_root/../.."
  if [ -f "$_project/pyproject.toml" ]; then
    _run checkout uv run --project "$_project" svg-mcp "$@"
  fi
fi

# An explicit release is never second-guessed: no PATH, no fallback. Without uvx it can't
# be fetched, so nothing runs (rather than quietly running some other version).
if [ -n "${SVG_MCP_VERSION:-}" ]; then
  if command -v uvx >/dev/null 2>&1; then
    _run version uvx "svg-mcp@${SVG_MCP_VERSION}" "$@"
  fi
  # probe mode: say there's no route (the hook reports it). Not `_run none true`, which
  # outside probe mode would exec true and exit 0 before the message below.
  if [ -n "${SVG_MCP_LAUNCHER_PROBE:-}" ]; then echo none; exit 0; fi
  echo "svg-mcp: SVG_MCP_VERSION=${SVG_MCP_VERSION} needs uvx to fetch that release." >&2
  echo "  Install uv (https://docs.astral.sh/uv/), or unset SVG_MCP_VERSION." >&2
  exit 127
fi

# An svg-mcp on PATH wins when it is at least the version this plugin ships against:
# the user's own `uv tool install svg-mcp`, and no fetch. Too old and we fall through to
# the pinned release rather than limp. Every svg-mcp on PATH is considered, skipping
# this launcher itself (same name) should its directory be on PATH.
# The loop only PICKS; the exec happens after it. Its list is read on fd 3, not stdin: a
# `done < <(...)` redirect would also become the exec'd svg-mcp's stdin, so input piped
# into the launcher would be swallowed (same fix as cribsheet's bin/crib).
_pick=""
while IFS= read -r -u 3 _real; do
  if ! [ -x "$_real" ] || [ "$_real" -ef "$0" ]; then continue; fi
  # at most 5 s: an svg-mcp that hangs counts as unusable (macOS has no timeout(1)).
  # Through a file, not a pipe: a killed svg-mcp's own children could hold a pipe open.
  _pv=""
  if _out="$(mktemp "${TMPDIR:-/tmp}/svg-mcp-ver.XXXXXX")"; then
    "$_real" --version >"$_out" 2>/dev/null </dev/null & _p=$!
    ( sleep 5; kill "$_p" 2>/dev/null ) >/dev/null 2>&1 & _k=$!
    if wait "$_p" 2>/dev/null; then _pv="$(awk '{print $NF}' "$_out")"; fi
    { kill "$_k"; wait "$_k"; } 2>/dev/null || true  # reaped quietly
    rm -f "$_out"
  fi
  if [ -n "$_pv" ] && { [ -z "$_ver" ] || _version_ge "$_pv" "$_ver"; }; then
    _pick="$_real"
  fi
  break  # the first real svg-mcp on PATH is the one a shell would run
done 3< <(type -ap svg-mcp 2>/dev/null || true)
if [ -n "$_pick" ]; then
  _run path "$_pick" "$@"
fi

if ! command -v uvx >/dev/null 2>&1; then
  # probe mode: say there's no route (the hook reports it). Not `_run none true`, which
  # outside probe mode would exec true and exit 0 before the message below.
  if [ -n "${SVG_MCP_LAUNCHER_PROBE:-}" ]; then echo none; exit 0; fi
  echo "svg-mcp: no usable 'svg-mcp' found, and uvx is unavailable to fetch it." >&2
  echo "  Install uv (https://docs.astral.sh/uv/) — the plugin then needs nothing else —" >&2
  echo "  or install svg-mcp directly: uv tool install svg-mcp" >&2
  exit 127
fi

# uvx caches, so this is one fetch and a cache hit thereafter. Pinned to this plugin's
# version; if that exact release is missing (a failed PyPI publish, say), the latest
# rather than nothing.
if [ -n "$_ver" ] && uvx "svg-mcp@${_ver}" --version >/dev/null 2>&1; then
  _run pinned uvx "svg-mcp@${_ver}" "$@"
fi
[ -n "$_ver" ] && echo "svg-mcp: the pinned release svg-mcp@${_ver} could not be fetched; trying the latest release" >&2
_run latest uvx svg-mcp "$@"
