#!/usr/bin/env bash
# work-plan CLI launcher. Resolves work_plan.py relative to this wrapper's PARENT
# (the wrapper lives at <root>/bin/work-plan, so the CLI is <root>/skills/...),
# then falls back to plugin-root env vars and the install.sh locations.

# GUI editors (VS Code launched from Finder/Dock, not a terminal) inherit a
# stripped PATH with no Homebrew — but the CLI shells out to python3/yq/gh,
# which on macOS live in /opt/homebrew/bin (Apple Silicon) or /usr/local/bin
# (Intel). Prepend the common tool dirs so a GUI-spawned CLI still finds them.
# Harmless elsewhere (missing dirs are simply ignored by PATH lookup).
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"

# Resolve symlinks before computing the package root: `npm install -g` puts the
# launcher in the global bin as a SYMLINK to the package, so $0 is the symlink,
# not the real file. Walk the symlink chain to the actual launcher so
# "<root>/skills/work-plan" resolves to the npm package, not the global bin dir.
src="${BASH_SOURCE[0]:-$0}"
while [ -L "$src" ]; do
  dir="$(cd -P "$(dirname "$src")" && pwd)"
  link="$(readlink "$src")"
  case "$link" in
    /*) src="$link" ;;
    *)  src="$dir/$link" ;;
  esac
done
root="$(cd -P "$(dirname "$src")/.." && pwd)"

# Runtime preflight: surface a clear, per-tool message if a required external
# tool is missing, instead of a Python traceback from deep in config-load (the
# classic "yq not found" confusion). yq/gh aren't needed for --version/--help,
# so don't block those.
_wp_have() { command -v "$1" >/dev/null 2>&1; }
_wp_missing=""
_wp_have python3 || _wp_missing="$_wp_missing python3"
case "${1:-}" in
  --version|-v|--help|-h|"") ;;
  *)
    _wp_have yq || _wp_missing="$_wp_missing yq"
    _wp_have gh || _wp_missing="$_wp_missing gh"
    ;;
esac
if [ -n "$_wp_missing" ]; then
  echo "work-plan: missing required tool(s) on PATH:$_wp_missing" >&2
  case "$_wp_missing" in *python3*) echo "  python3 — the CLI runtime            (brew install python · https://python.org)" >&2 ;; esac
  case "$_wp_missing" in *yq*)      echo "  yq      — YAML config/frontmatter    (brew install yq — the Go mikefarah/yq, NOT the python yq)" >&2 ;; esac
  case "$_wp_missing" in *gh*)      echo "  gh      — GitHub issue state         (brew install gh, then: gh auth login · https://cli.github.com)" >&2 ;; esac
  exit 1
fi

for c in \
  "$root/skills/work-plan/work_plan.py" \
  "${CLAUDE_PLUGIN_ROOT:-}/skills/work-plan/work_plan.py" \
  "${PLUGIN_ROOT:-}/skills/work-plan/work_plan.py" \
  "$HOME/.claude/skills/work-plan/work_plan.py" \
  "$HOME/.agents/skills/work-plan/work_plan.py"; do
  [ -n "$c" ] && [ -f "$c" ] && exec python3 "$c" "$@"
done
echo "work-plan: CLI not found (looked next to bin/.., CLAUDE_PLUGIN_ROOT, PLUGIN_ROOT, ~/.claude, ~/.agents)." >&2
exit 1
