#!/usr/bin/env bash
# Guidebook gaps
# Which units have no guidebook attached. Every unit without one is a guest ringing the front desk to ask the wifi password.
#
# Category : Operations
# Safety   : read only
# Uses     : reports run, guidebooks list, guidebooks unit-assignments
# Returns  : Units with no guidebook, and guidebooks assigned to nothing.
#
# Requires the SendSquared CLI and jq:
#   curl -fsSL https://cli.sendsquared.com/install.sh | bash
#   sendsquared auth login
#
# Free to use and adapt. https://sendsquared.com/cli/scripts/#guidebook-gaps

# Guidebook coverage: how many stays actually open the book.
set -euo pipefail
FROM=${1:-$(date -u -v-90d +%F 2>/dev/null || date -u -d "-90 days" +%F)}
TO=${2:-$(date -u +%F)}

echo "--- saturation by guidebook, $FROM to $TO"
sendsquared reports run guidebook_saturation --from "$FROM" --to "$TO" \
| jq -r '
  .data[]
  | [ (.guidebook_name // ("guidebook " + (.guidebook_id|tostring))),
      (.total_reservations // 0), (.opened_reservations // 0), (.saturation_pct // 0) ]
  | @tsv
' \
| sort -t$'\t' -k4 -n \
| awk -F'\t' 'BEGIN{printf "  %-40s %8s %8s %8s\n","GUIDEBOOK","STAYS","OPENED","PCT"}
    {printf "  %-40s %8s %8s %7s%%\n",$1,$2,$3,$4}'

echo
echo "--- guidebooks with no units assigned"
sendsquared guidebooks list --limit 200 \
| jq -r '.data.guidebooks[]? | [.id, (.name // .public_name // "untitled")] | @tsv' \
> /tmp/.gb.tsv
UNASSIGNED=0
while IFS=$'\t' read -r ID NAME; do
  [ -z "$ID" ] && continue
  N=$(sendsquared guidebooks unit-assignments "$ID" 2>/dev/null | jq '[.data[]?] | length' 2>/dev/null || echo 0)
  if [ "${N:-0}" -eq 0 ]; then echo "  $ID  $NAME"; UNASSIGNED=$((UNASSIGNED+1)); fi
done < /tmp/.gb.tsv
if [ "$UNASSIGNED" -eq 0 ]; then echo "  none, every guidebook has units"; fi
rm -f /tmp/.gb.tsv
