#!/usr/bin/env bash
#
# E8 Markets MCP — connection smoke test.
#
#   export E8_API_KEY="e8_..."
#   ./smoke-test.sh
#
# Read-only. Places no orders. Requires curl and jq.

set -uo pipefail

ENDPOINT="${E8_MCP_ENDPOINT:-https://trade.e8markets.com/api/mcp}"

if [ -z "${E8_API_KEY:-}" ]; then
  echo "E8_API_KEY is not set. Mint a key at https://trade.e8markets.com/settings" >&2
  exit 1
fi

command -v jq >/dev/null || { echo "jq is required but not installed." >&2; exit 1; }

pass() { printf '\033[32m✓\033[0m %s\n' "$1"; }
fail() { printf '\033[31m✗\033[0m %s\n' "$1"; }
warn() { printf '\033[33m⚠\033[0m %s\n' "$1"; }

# Call one MCP tool. Echoes the tool's text payload, or nothing on failure.
call() {
  local tool="$1" args="${2:-{\}}"
  curl -s --max-time 30 "$ENDPOINT" \
    -H "Authorization: Bearer $E8_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json, text/event-stream" \
    -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",
         \"params\":{\"name\":\"$tool\",\"arguments\":$args}}"
}

echo "Testing $ENDPOINT"
echo

# --- 1. Endpoint reachable, credential accepted, tools discoverable ----------
LIST=$(curl -s --max-time 30 "$ENDPOINT" \
  -H "Authorization: Bearer $E8_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}')

if [ -z "$LIST" ]; then
  fail "Endpoint unreachable — no response"
  exit 1
fi

if ! echo "$LIST" | jq -e . >/dev/null 2>&1; then
  fail "Endpoint returned non-JSON (edge security challenge?)"
  echo "$LIST" | head -c 200
  exit 1
fi
pass "Endpoint reachable"

if echo "$LIST" | jq -e '.error' >/dev/null 2>&1; then
  fail "Credential rejected: $(echo "$LIST" | jq -r '.error.message')"
  exit 1
fi
pass "Credential accepted"

TOOL_COUNT=$(echo "$LIST" | jq '.result.tools | length')
if [ "$TOOL_COUNT" -gt 0 ]; then
  pass "$TOOL_COUNT tools available"
else
  fail "No tools returned"
  exit 1
fi

# --- 2. Market data ---------------------------------------------------------
ASSET=$(call e8_trade_asset_get '{"symbol":"EURUSD"}')
if echo "$ASSET" | jq -e '.result' >/dev/null 2>&1; then
  PRICE=$(echo "$ASSET" | jq -r '.result.content[0].text' \
          | jq -r '.lastPrice // "n/a"' 2>/dev/null || echo "n/a")
  pass "Market data readable    (EURUSD @ $PRICE)"
else
  fail "Market data unreadable: $(echo "$ASSET" | jq -r '.error.message // "unknown"')"
fi

# --- 3. Account data (needs read:trade) -------------------------------------
ACCOUNTS=$(call e8_accounts_list)
if echo "$ACCOUNTS" | jq -e '.result' >/dev/null 2>&1; then
  TEXT=$(echo "$ACCOUNTS" | jq -r '.result.content[0].text')
  if echo "$TEXT" | grep -qi "insufficient permissions"; then
    warn "Account data blocked   — key lacks read:trade"
  else
    N=$(echo "$TEXT" | jq -r '(.accounts // []) | length' 2>/dev/null || echo "?")
    pass "Account data readable   ($N accounts)"
  fi
else
  warn "Account data unreadable: $(echo "$ACCOUNTS" | jq -r '.error.message // "unknown"')"
fi

# --- 4. Can this key trade? -------------------------------------------------
# Probed without side effects: cancelling a non-existent order fails on scope
# before it fails on the order id.
PROBE=$(call e8_order_cancel '{"orderId":"smoke-test-nonexistent"}')
PROBE_TEXT=$(echo "$PROBE" | jq -r '.result.content[0].text // .error.message // ""')

if echo "$PROBE_TEXT" | grep -qi "insufficient permissions"; then
  pass "Read-only key           — cannot place or close orders"
else
  warn "trade:execute present   — this key CAN place and close orders"
fi

echo
echo "Done. See 05_safety_and_limits.md if the scope warning was unexpected."
