#!/usr/bin/env bash
# Dispatcher for hermit boot scripts — resolves plugin path by scanning installed plugins
# Usage: hermit-run <script.py> [args...]
# Called by hermit-start and hermit-stop wrappers.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG="$SCRIPT_DIR/../config.json"
TARGET="${1:?Usage: hermit-run <script.py> [args...]}"
shift

if [ ! -f "$CONFIG" ]; then
  echo "[hermit] No config found at $CONFIG" >&2
  echo "[hermit] Run /claude-code-hermit:hatch inside Claude Code first." >&2
  exit 1
fi

# --- Resolve plugin root ---
# Priority: HERMIT_PLUGIN_ROOT env var > scan ~/.claude/plugins/
# No config.json dependency — works in both host and Docker without path conflicts.

PLUGIN_ROOT=""

# 1. Env var (set by docker-entrypoint)
if [ -n "${HERMIT_PLUGIN_ROOT:-}" ] && [ -d "$HERMIT_PLUGIN_ROOT" ]; then
  PLUGIN_ROOT="$HERMIT_PLUGIN_ROOT"
fi

# 2. Scan marketplace cache for the claude-code-hermit plugin under
# plugins/<name>/ (monorepo layout — gtapps/claude-code-hermit ships as a
# multi-plugin marketplace).
if [ -z "$PLUGIN_ROOT" ]; then
  SEARCH_BASE="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
  _old_nullglob=$(shopt -p nullglob 2>/dev/null || true)
  shopt -s nullglob
  for d in "$SEARCH_BASE"/plugins/marketplaces/*/plugins/*/; do
    if [ -d "$d/scripts" ] && [ -f "$d/.claude-plugin/plugin.json" ]; then
      FOUND_NAME=$(grep -o '"name"[^,]*' "$d/.claude-plugin/plugin.json" 2>/dev/null | head -1 | cut -d'"' -f4)
      [ "$FOUND_NAME" = "claude-code-hermit" ] && PLUGIN_ROOT="${d%/}" && break
    fi
  done
  $_old_nullglob
fi

if [ -z "$PLUGIN_ROOT" ] || [ ! -d "$PLUGIN_ROOT" ]; then
  echo "[hermit] Plugin root not found or invalid: $PLUGIN_ROOT" >&2
  echo "[hermit] Run /claude-code-hermit:hermit-evolve inside Claude Code to fix." >&2
  exit 1
fi

SCRIPT="$PLUGIN_ROOT/scripts/$TARGET"
if [ ! -f "$SCRIPT" ]; then
  echo "[hermit] $TARGET not found at $PLUGIN_ROOT/scripts/" >&2
  echo "[hermit] Plugin may be corrupted. Reinstall with: claude plugin install claude-code-hermit@claude-code-hermit --scope project" >&2
  exit 1
fi

exec python3 "$SCRIPT" "$@"
