#!/usr/bin/env bash
set -u
GATE="$(cd "$(dirname "$0")/.." && pwd)/check-no-raw-mcp-registrations.mjs"
[[ -f "$GATE" ]] || { echo "FAIL: gate script missing at $GATE" >&2; exit 1; }
PASS=0; FAIL=0

ROOT=$(mktemp -d)
trap 'rm -rf "$ROOT"' EXIT

make_plugin() {
  local plugin="$1" content="$2"
  local dir="$ROOT/platform/plugins/$plugin/mcp/src"
  mkdir -p "$dir"
  printf '%s\n' "$content" > "$dir/index.ts"
}

reset_root() {
  rm -rf "$ROOT/platform"
}

check() {
  local desc="$1" expected="$2"
  shift 2
  node "$GATE" --root "$ROOT" "$@" >/dev/null 2>&1
  local got=$?
  if [[ "$got" -eq "$expected" ]]; then
    echo "PASS: $desc"
    ((PASS++))
  else
    echo "FAIL: $desc (expected exit $expected, got $got)"
    ((FAIL++))
  fi
}

# CASE 1: raw server.tool( in a plugin → gate fails
reset_root
make_plugin "bad-plugin" 'server.tool("foo", "desc", {}, async () => ({}));'
check "raw server.tool triggers failure" 1

# CASE 2: lifelineTool in a plugin → gate passes
reset_root
make_plugin "good-plugin" 'lifelineTool(server, "foo", "desc", {}, async () => ({}));'
check "lifelineTool passes gate" 0

# CASE 3: server.registerTool( in a plugin → gate fails
reset_root
make_plugin "bad-plugin2" 'server.registerTool("foo", {}, async () => ({}));'
check "raw server.registerTool triggers failure" 1

# CASE 4: eagerTool in a plugin → gate passes
reset_root
make_plugin "eager-plugin" 'eagerTool(server, "foo", "desc", {}, async () => ({}));'
check "eagerTool passes gate" 0

echo ""
echo "Results: $PASS passed, $FAIL failed"
[[ "$FAIL" -eq 0 ]] && exit 0 || exit 1
