#!/usr/bin/env bash
# =============================================================================
# UptimeRobot Monitor Setup Script
# Usage: UPTIMEROBOT_API_KEY=your_key ./scripts/setup-uptimerobot.sh
#
# Creates monitors for:
#   - Main site health check (every 5 min)
#   - Homepage
#   - API health endpoint
#   - SSL certificate expiry alert
# =============================================================================

set -euo pipefail

API_KEY="${UPTIMEROBOT_API_KEY:-}"
ALERT_EMAIL="${ALERT_EMAIL:-}"
BASE_URL="https://workroot.in"
API_BASE="https://api.uptimerobot.com/v2"

# ── Validation ────────────────────────────────────────────────────────────────
if [ -z "$API_KEY" ]; then
  echo "ERROR: UPTIMEROBOT_API_KEY environment variable is required"
  echo "Get your API key from: https://uptimerobot.com/dashboard → My Settings → API Settings"
  exit 1
fi

# ── Helper function ───────────────────────────────────────────────────────────
uptimerobot_api() {
  local endpoint="$1"
  shift
  curl -s -X POST "${API_BASE}/${endpoint}" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    --data "api_key=${API_KEY}&format=json&$*"
}

# ── Get or create alert contact ───────────────────────────────────────────────
get_alert_contact_id() {
  if [ -z "$ALERT_EMAIL" ]; then
    # Use first existing contact
    CONTACTS=$(uptimerobot_api "getAlertContacts")
    CONTACT_ID=$(echo "$CONTACTS" | python3 -c "
import sys, json
data = json.load(sys.stdin)
contacts = data.get('alert_contacts', [])
if contacts:
    print(contacts[0]['id'])
" 2>/dev/null || echo "")
    echo "$CONTACT_ID"
    return
  fi

  # Create new contact for the email
  RESULT=$(uptimerobot_api "newAlertContact" \
    "type=2&value=${ALERT_EMAIL}&friendly_name=WorkRoot+Alerts")
  CONTACT_ID=$(echo "$RESULT" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(data.get('alertcontact', {}).get('id', ''))
" 2>/dev/null || echo "")
  echo "$CONTACT_ID"
}

# ── Create monitor ────────────────────────────────────────────────────────────
create_monitor() {
  local name="$1"
  local url="$2"
  local type="${3:-1}"           # 1=HTTP, 2=keyword, 3=ping
  local interval="${4:-300}"     # seconds
  local alert_id="$5"
  local keyword="${6:-}"

  echo "Creating monitor: $name → $url"

  local data="friendly_name=${name}&url=${url}&type=${type}&interval=${interval}"
  if [ -n "$alert_id" ]; then
    data="${data}&alert_contacts=${alert_id}_0_0"
  fi
  if [ "$type" = "2" ] && [ -n "$keyword" ]; then
    data="${data}&keyword_type=1&keyword_value=${keyword}"
  fi

  RESULT=$(uptimerobot_api "newMonitor" "$data")
  STATUS=$(echo "$RESULT" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(data.get('stat', 'fail'))
" 2>/dev/null || echo "fail")

  if [ "$STATUS" = "ok" ]; then
    MONITOR_ID=$(echo "$RESULT" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(data.get('monitor', {}).get('id', ''))
" 2>/dev/null || echo "")
    echo "  Created monitor ID: $MONITOR_ID"
  else
    ERROR=$(echo "$RESULT" | python3 -c "
import sys, json
data = json.load(sys.stdin)
err = data.get('error', {})
print(err.get('message', 'unknown error'))
" 2>/dev/null || echo "unknown")
    echo "  WARNING: Failed to create monitor - $ERROR"
  fi
}

# ── Main ──────────────────────────────────────────────────────────────────────
echo "============================================"
echo " WorkRoot UptimeRobot Monitor Setup"
echo "============================================"
echo ""

echo "Getting alert contact..."
ALERT_ID=$(get_alert_contact_id)
if [ -z "$ALERT_ID" ]; then
  echo "WARNING: No alert contact found/created. Monitors will be created without alerts."
  echo "Add an alert contact at: https://uptimerobot.com/dashboard → Alert Contacts"
fi
echo "Alert contact ID: ${ALERT_ID:-none}"
echo ""

# HTTP monitors (every 5 minutes)
create_monitor "WorkRoot - Health Check" "${BASE_URL}/api/health.json" "1" "300" "$ALERT_ID"
create_monitor "WorkRoot - Homepage" "${BASE_URL}/" "1" "300" "$ALERT_ID"
create_monitor "WorkRoot - Services Page" "${BASE_URL}/services" "1" "300" "$ALERT_ID"
create_monitor "WorkRoot - Contact Page" "${BASE_URL}/contact" "1" "300" "$ALERT_ID"

# Keyword monitor - verify health endpoint returns "ok" status
create_monitor "WorkRoot - Health Status OK" "${BASE_URL}/api/health.json" "2" "300" "$ALERT_ID" "\"status\":\"ok\""

# SSL certificate monitor (UptimeRobot checks SSL with HTTP monitors, but
# we add explicit keyword check for https redirect)
create_monitor "WorkRoot - SSL/HTTPS" "https://workroot.in/" "1" "300" "$ALERT_ID"

echo ""
echo "============================================"
echo " Setup complete!"
echo ""
echo "Next steps:"
echo "  1. Login to UptimeRobot: https://uptimerobot.com/dashboard"
echo "  2. Enable SSL certificate expiry alerts for each HTTPS monitor"
echo "     Monitor → Edit → Enable SSL monitoring → Set alert threshold to 14 days"
echo "  3. Configure response time alert threshold:"
echo "     Monitor → Edit → Response Time Threshold → 3000ms"
echo "  4. Set up status page: Dashboard → Status Pages → Create"
echo "============================================"
