#!/usr/bin/env bash
# probe-ghl-scopes.sh — one-shot capability probe for the stored GHL token.
# Run: bash scripts/probe-ghl-scopes.sh
# Reads /root/.hermes/secrets/ghl.env (GHL_TOKEN, GHL_API_BASE, GHL_API_VERSION).
# Prints ✓/✗ per capability so you can tell the user exactly which scopes to tick.

set -u
ENV_FILE="${GHL_ENV_FILE:-/root/.hermes/secrets/ghl.env}"
if [ ! -r "$ENV_FILE" ]; then
  echo "missing $ENV_FILE — create it with GHL_TOKEN=..., GHL_API_BASE=..., GHL_API_VERSION=..." >&2
  exit 1
fi
# shellcheck disable=SC1090
source "$ENV_FILE"
: "${GHL_API_BASE:=https://services.leadconnectorhq.com}"
: "${GHL_API_VERSION:=2021-07-28}"

probe () {
  local label="$1" path="$2"
  local body code
  body=$(curl -s -w $'\n%{http_code}' \
    -H "Authorization: Bearer $GHL_TOKEN" \
    -H "Version: $GHL_API_VERSION" \
    -H "Accept: application/json" \
    "$GHL_API_BASE$path")
  code="${body##*$'\n'}"
  body="${body%$'\n'*}"
  if [ "$code" = "200" ]; then
    echo "✓ $label"
    echo "$body" | head -c 400
    echo ""
  else
    echo "✗ $label  [HTTP $code] $(echo "$body" | head -c 160)"
    # Distinguish the two 401s — they have DIFFERENT fixes:
    if echo "$body" | grep -q "Invalid Private Integration token"; then
      echo "    → INVALID TOKEN: string rejected (wrong/transcribed/not-yet-active). Get exact token via GHL Copy button as TEXT — never OCR from a screenshot."
    elif echo "$body" | grep -q "not authorized for this scope"; then
      echo "    → SCOPE GAP: token valid, missing scope. NOTE (2026-07): re-saving scopes often does NOT take on an existing token — mint a FRESH token after selecting scopes."
    fi
  fi
}

echo "=== GHL scope probe ==="
# 1) token validity — /locations/search works with nearly any valid token
probe "locations/search (token validity + subaccount info)" "/locations/search?limit=1"

# 2) capability probes — need locationId; extract from the first probe if possible
LOC=$(curl -s -H "Authorization: Bearer $GHL_TOKEN" -H "Version: $GHL_API_VERSION" \
  "$GHL_API_BASE/locations/search?limit=1" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$LOC" ]; then
  echo "could not extract locationId — token likely invalid; fix token before scope checks" >&2
  exit 2
fi
echo "locationId: $LOC"
echo ""

probe "funnels list     " "/funnels/funnel/list?locationId=$LOC"
probe "funnel pages     " "/funnels/page?locationId=$LOC&funnelId=dummy&limit=1&offset=0"
probe "contacts         " "/contacts/?locationId=$LOC&limit=1"
probe "forms            " "/forms/?locationId=$LOC&limit=1"
probe "calendars        " "/calendars/?locationId=$LOC"

echo ""
echo "✗ rows legend:"
echo "  'not authorized for this scope' = scope gap. Fix: select scope in GHL, THEN mint a FRESH token (re-saving the existing token usually does NOT expand its scopes — 2026-07)."
echo "  'Invalid Private Integration token' = bad/not-yet-active token string. Fix: GHL Copy button → paste as TEXT (never transcribe from a screenshot)."
