#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════
# Fleet Snapshot Writer
# ══════════════════════════════════════════════════════════════
# Runs every 2 min via cron on VPS. Queries each agent's gateway
# status endpoint and writes snapshots to cc_agent_snapshots via
# Supabase REST API.
#
# Crontab: */2 * * * * /home/ccuser/rateright-growth/rivet/scripts/fleet-snapshot.sh
#
# Env vars (set in crontab or /root/.profile):
#   SUPABASE_URL          — e.g. https://xxx.supabase.co
#   SUPABASE_SERVICE_KEY  — service role key (bypasses RLS)
# ══════════════════════════════════════════════════════════════

set -euo pipefail

SUPABASE_URL="${SUPABASE_URL:?Missing SUPABASE_URL}"
SUPABASE_SERVICE_KEY="${SUPABASE_SERVICE_KEY:?Missing SUPABASE_SERVICE_KEY}"

# Agent registry — must match fleet.config.js
declare -A AGENTS=(
  [rivet]=18789
  [builder]=18790
  [susan]=18792
  [harper]=18796
  [sentinel]=18800
  [radar]=18804
  [herald]=18808
  [cog]=18812
)

declare -A SERVICES=(
  [rivet]=clawdbot-gateway
  [builder]=clawdbot-builder
  [susan]=clawdbot-susan
  [harper]=clawdbot-harper
  [sentinel]=clawdbot-sentinel
  [radar]=clawdbot-radar
  [herald]=clawdbot-herald
  [cog]=clawdbot-cog
)

NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

for agent in "${!AGENTS[@]}"; do
  port="${AGENTS[$agent]}"
  service="${SERVICES[$agent]}"
  status="offline"
  uptime_seconds=0
  current_task=""
  memory_mb=0
  cpu_percent=0

  # Check if systemd service is active
  if systemctl is-active "$service" &>/dev/null; then
    status="healthy"

    # Get uptime
    enter_ts=$(systemctl show "$service" --property=ActiveEnterTimestamp --value 2>/dev/null || echo "")
    if [ -n "$enter_ts" ]; then
      enter_epoch=$(date -d "$enter_ts" +%s 2>/dev/null || echo 0)
      now_epoch=$(date +%s)
      uptime_seconds=$(( now_epoch - enter_epoch ))
    fi

    # Try to get memory usage from systemd
    mem_bytes=$(systemctl show "$service" --property=MemoryCurrent --value 2>/dev/null || echo 0)
    if [ "$mem_bytes" != "[not set]" ] && [ "$mem_bytes" -gt 0 ] 2>/dev/null; then
      memory_mb=$(( mem_bytes / 1048576 ))
    fi

    # Try port health check (2s timeout)
    if ! curl -sf --max-time 2 "http://127.0.0.1:${port}/health" &>/dev/null; then
      # Port not responding but service is up — warning state
      status="warning"
      current_task="Service running but port not responding"
    fi
  fi

  # Build JSON payload
  payload=$(cat <<ENDJSON
{
  "agent_name": "$agent",
  "status": "$status",
  "port": $port,
  "uptime_seconds": $uptime_seconds,
  "memory_mb": $memory_mb,
  "cpu_percent": $cpu_percent,
  "current_task": "$current_task",
  "snapshot_at": "$NOW"
}
ENDJSON
)

  # POST to Supabase
  curl -sf --max-time 5 \
    -X POST "${SUPABASE_URL}/rest/v1/cc_agent_snapshots" \
    -H "apikey: ${SUPABASE_SERVICE_KEY}" \
    -H "Authorization: Bearer ${SUPABASE_SERVICE_KEY}" \
    -H "Content-Type: application/json" \
    -H "Prefer: return=minimal" \
    -d "$payload" || echo "[fleet-snapshot] Failed to write snapshot for $agent" >&2

done
