#!/usr/bin/env bash
# Launch the phpkg MCP server for the Claude Code plugin.
#
# "One-click install" has to mean the user installs a plugin and it works --
# no pip, no venv, no PATH surgery. Three strategies, cheapest first:
#
#   1. uvx        -- no install at all; uv fetches phpkg into a cache and runs it.
#   2. venv       -- a private venv under ${CLAUDE_PLUGIN_DATA}, built once from
#                    the plugin's own source. Covers "not published to PyPI yet"
#                    and "offline", and is what a git-clone install uses.
#   3. phpkg      -- already on PATH (developer machines).
#
# Everything diagnostic goes to stderr: stdout is the MCP stdio channel, and a
# single stray byte there corrupts the protocol and the server dies with a
# parse error that looks nothing like its cause.
set -euo pipefail

log() { printf '[phpkg-mcp] %s\n' "$*" >&2; }

PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
DATA_DIR="${CLAUDE_PLUGIN_DATA:-${PLUGIN_ROOT}/.data}"
VENV="${DATA_DIR}/venv"

# Strategy 3 first when it is a real install (fastest, zero setup).
if command -v phpkg >/dev/null 2>&1; then
  exec phpkg serve "$@"
fi

# Strategy 1: uvx. --from is required because the package and the command
# share a name only by convention.
if command -v uvx >/dev/null 2>&1 && [ "${PHPKG_NO_UVX:-}" != "1" ]; then
  if [ -f "${PLUGIN_ROOT}/pyproject.toml" ]; then
    # Installed from a git clone: run the bundled source, not whatever
    # version happens to be on PyPI, so the tools match the shipped skill.
    exec uvx --from "${PLUGIN_ROOT}" phpkg serve "$@"
  fi
  exec uvx --from phpkg phpkg serve "$@"
fi

# Strategy 2: private venv, built once.
if [ ! -x "${VENV}/bin/phpkg" ]; then
  log "first run: building a private environment in ${VENV}"
  PY=""
  for candidate in python3.12 python3.11 python3.10 python3; do
    if command -v "$candidate" >/dev/null 2>&1; then PY="$candidate"; break; fi
  done
  if [ -z "$PY" ]; then
    log "ERROR: no python3 found. Install Python 3.10+ or uv (https://docs.astral.sh/uv/)."
    exit 1
  fi
  mkdir -p "${DATA_DIR}"
  "$PY" -m venv "${VENV}" >&2
  SOURCE="${PLUGIN_ROOT}"
  [ -f "${PLUGIN_ROOT}/pyproject.toml" ] || SOURCE="phpkg"
  "${VENV}/bin/pip" install --quiet --upgrade pip >&2
  "${VENV}/bin/pip" install --quiet "${SOURCE}" >&2
  log "environment ready"
fi

exec "${VENV}/bin/phpkg" serve "$@"
