#!/usr/bin/env bash
# ghl-probe.sh — verify the GHL token is alive and report which scopes work.
# Run FIRST on any GHL task before promising capabilities.
# Usage: bash scripts/ghl-probe.sh   (sources /root/.hermes/secrets/ghl.env itself)
set -u
ENV_FILE="/root/.hermes/secrets/ghl.env"
if [ ! -r "$ENV_FILE" ]; then echo "MISSING: $ENV_FILE — ask the user for a Private Integration token."; exit 1; fi
# shellcheck disable=SC1090
source "$ENV_FILE"
LOC="${GHL_LOCATION_ID:-4yTvHUHrmVuP8CgCt1Q9}"   # Real Results Ready LLC

probe () {
  local label="$1" path="$2"
  local code body
  body=$(curl -s -o /tmp/ghl_probe.json -w "%{http_code}" \
    -H "Authorization: Bearer $GHL_TOKEN" \
    -H "Version: ${GHL_API_VERSION:-2021-07-28}" \
    -H "Accept: application/json" \
    "${GHL_API_BASE:-https://services.leadconnectorhq.com}${path}")
  code="$body"
  local msg
  msg=$(head -c 90 /tmp/ghl_probe.json | tr '\n' ' ')
  printf "%-14s HTTP %s  %s\n" "$label" "$code" "$msg"
}

echo "=== GHL auth+scope probe (location $LOC) ==="
probe "identity"   "/locations/search?limit=1"
probe "funnels"    "/funnels/funnel/list?locationId=$LOC"
probe "contacts"   "/contacts/?locationId=$LOC&limit=1"
probe "forms"      "/forms/?locationId=$LOC&limit=1"
probe "calendars"  "/calendars/?locationId=$LOC"
probe "campaigns"  "/campaigns/?locationId=$LOC"
echo
echo "Reading results:"
echo "  'Invalid Private Integration token'  -> token string wrong/dead (check transcription, ask for fresh copy-paste)"
echo "  'not authorized for this scope'      -> token VALID, scope missing. If user says they added scopes: they must create a NEW token (scopes lock at creation)."
echo "  200 on identity only                 -> the scope-lock pitfall; see SKILL.md pitfall #1"
