#!/usr/bin/env bash
# Source this file after OAuth login:
#   source ./docintel-mcp-client.sh

export MCP_URL="${MCP_URL:-https://mcp.docintel.adar.agomoniai.com/mcp}"
export MCP_PROTOCOL_VERSION="${MCP_PROTOCOL_VERSION:-2025-06-18}"

mcp_request() {
  if [[ -z "${MCP_ACCESS_TOKEN:-}" ]]; then
    echo "MCP_ACCESS_TOKEN is not loaded. Run OAuth login first." >&2
    return 1
  fi

  curl -sS -X POST "$MCP_URL" \
    -H "Authorization: Bearer $MCP_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json, text/event-stream" \
    -H "MCP-Protocol-Version: $MCP_PROTOCOL_VERSION" \
    --data "$1"
}

mcp_tool() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: mcp_tool <tool-name> [arguments-json]" >&2
    return 1
  fi

  local name="$1"
  local arguments="${2:-{}}"

  if ! jq -e . >/dev/null 2>&1 <<<"$arguments"; then
    echo "Tool arguments must be valid JSON" >&2
    return 1
  fi

  mcp_request "$(jq -cn \
    --arg name "$name" \
    --argjson arguments "$arguments" \
    '{jsonrpc:"2.0",id:1,method:"tools/call",params:{name:$name,arguments:$arguments}}')"
}

tool_data() {
  jq '
    if .error then
      {ok:false,error:.error}
    elif .result.structuredContent.result? then
      .result.structuredContent.result
    elif .result.structuredContent? then
      .result.structuredContent
    elif (.result.content[0].text? | type) == "string" then
      (.result.content[0].text | try fromjson catch {text:.})
    else
      .result
    end
  '
}
