#!/usr/bin/env sh
set -eu

BASE_URL="${FRISKY_MCP_BASE:-https://mcp.friskydev.com}"
TOKEN="${FRISKY_BOT_API_TOKEN:-${FRISKY_MCP_BOT_TOKEN:-}}"
TOKEN="${FRISKY_ACCESS_TOKEN:-$TOKEN}"

usage() {
  cat <<'EOF'
Frisky MCP CLI

Usage:
  frisky-mcp status
  frisky-mcp specialists
  frisky-mcp openapi
  frisky-mcp mcp-config
  frisky-mcp consult <slug> <request>
  frisky-mcp packet <slug> <request>

Environment:
  FRISKY_ACCESS_TOKEN    OAuth access token from the Frisky login flow
  FRISKY_BOT_API_TOKEN   Machine bearer token for live consult calls
  FRISKY_MCP_BASE        Optional base URL, default https://mcp.friskydev.com

Examples:
  FRISKY_BOT_API_TOKEN=... frisky-mcp consult frisky-director "Prioritize beta work"
  frisky-mcp packet frisky-codex-engineer "Review deployment risk"
EOF
}

json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

command="${1:-help}"
if [ "$#" -gt 0 ]; then
  shift
fi

case "$command" in
  help|-h|--help)
    usage
    ;;
  status)
    curl -fsS "$BASE_URL/api/model/status"
    ;;
  specialists)
    curl -fsS "$BASE_URL/api/specialists"
    ;;
  openapi)
    curl -fsS "$BASE_URL/openapi.json"
    ;;
  mcp-config)
    curl -fsS "$BASE_URL/codex.mcp.json"
    ;;
  packet|consult)
    if [ "$#" -lt 2 ]; then
      usage >&2
      exit 2
    fi
    slug="$1"
    shift
    request="$*"
    live_call="false"
    auth_header=""
    if [ "$command" = "consult" ]; then
      live_call="true"
      if [ -z "$TOKEN" ]; then
        echo "Missing FRISKY_BOT_API_TOKEN for live consult." >&2
        exit 2
      fi
      auth_header="Authorization: Bearer $TOKEN"
    fi
    body="{\"slug\":\"$(json_escape "$slug")\",\"request\":\"$(json_escape "$request")\",\"live_call\":$live_call}"
    if [ -n "$auth_header" ]; then
      curl -fsS -X POST "$BASE_URL/consult_specialist" \
        -H "$auth_header" \
        -H "Content-Type: application/json" \
        -d "$body"
    else
      curl -fsS -X POST "$BASE_URL/consult_specialist" \
        -H "Content-Type: application/json" \
        -d "$body"
    fi
    ;;
  *)
    usage >&2
    exit 2
    ;;
esac
