#!/usr/bin/env bash
# Workflow MCP tool test suite.
#
# Exercises all 8 workflow tools via the MCP protocol to verify:
#   - Creation: valid, missing plugin (draft), cycle detection, step limit
#   - Type enforcement: "skill" and "subagent" rejected at schema level
#   - Timeout validation: boundary checks (0, 120, 121, omitted)
#   - Get / List / Update / Delete
#   - Validation: re-validate draft workflows
#   - Execution: draft/paused rejection
#   - Run history queries
#
# Prerequisites: Neo4j running, Ollama running (for embeddings).
# Uses the MCP SDK Client to communicate with the server — same protocol
# path production uses.
#
# Usage: bash test-workflows.sh
# Exit 0 = all tests pass, exit 1 = failure

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Workflow Test Suite ==="
echo ""

# ── Check prerequisites ──────────────────────────────────────

# Neo4j connectivity check
echo -n "Checking Neo4j... "
# NEO4J_URI is hard-required. No default — set explicitly before running tests.
if [ -z "${NEO4J_URI:-}" ]; then
  echo "Error: NEO4J_URI required (no default)" >&2
  exit 1
fi
if ! nc -z "$(echo "$NEO4J_URI" | sed 's|.*://||;s|:.*||')" "$(echo "$NEO4J_URI" | sed 's|.*:||')" 2>/dev/null; then
  echo "SKIP — Neo4j not reachable at $NEO4J_URI"
  echo "Tests require Neo4j. Run on the Pi or start Neo4j locally."
  exit 0
fi
echo "OK"

# Ollama check (needed for embeddings at workflow creation time)
OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"
echo -n "Checking Ollama... "
if ! curl -sf "$OLLAMA_URL/api/tags" >/dev/null 2>&1; then
  echo "SKIP — Ollama not reachable at $OLLAMA_URL"
  echo "Tests require Ollama for embedding generation."
  exit 0
fi
echo "OK"

# Build check
echo -n "Checking build... "
if [ ! -f "$SCRIPT_DIR/dist/index.js" ]; then
  echo "not built — building now..."
  (cd "$SCRIPT_DIR" && npm run build 2>&1) || {
    echo "Build failed"
    exit 1
  }
  echo "  Build complete"
else
  echo "OK"
fi

# PLATFORM_ROOT must be set
if [ -z "${PLATFORM_ROOT:-}" ]; then
  # Derive from script location: mcp/ → workflows/ → plugins/ → platform/
  export PLATFORM_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
  echo "PLATFORM_ROOT set to: $PLATFORM_ROOT"
fi

echo ""

# ── Run tests ─────────────────────────────────────────────────

node "$SCRIPT_DIR/test-runner.mjs"
