#!/usr/bin/env bash
# Send the adapter one alert shaped exactly as alertstore sends them, without
# needing alertstore. Pair it with the callback sink to watch the whole loop:
#
#   make sink     # terminal 1
#   make run      # terminal 2
#   make e2e      # terminal 3
#
# Try it against a real alert by passing the `alert` object from one — the
# easiest source is GET /api/v1/alertstore/alerts/<id>:
#
#   ./hack/fake-dispatch.sh --alert-file ./alert.json
#
# Options: --adapter URL  --sink URL  --alert-file PATH  --alert-id ID

set -euo pipefail

ADAPTER="${ADAPTER:-http://127.0.0.1:8899}"
SINK="${SINK:-http://127.0.0.1:8898}"
ALERT_ID="${ALERT_ID:-ALT-2607-42}"
RUN_ID="${RUN_ID:-1}"
ALERT_FILE=""

while [ $# -gt 0 ]; do
  case "$1" in
    --alert-file) ALERT_FILE="$2"; shift 2 ;;
    --alert-id)   ALERT_ID="$2"; shift 2 ;;
    --adapter)    ADAPTER="$2"; shift 2 ;;
    --sink)       SINK="$2"; shift 2 ;;
    -h|--help)    sed -n '2,17p' "$0"; exit 0 ;;
    *) echo "unknown argument: $1" >&2; exit 2 ;;
  esac
done

if [ -n "$ALERT_FILE" ]; then
  ALERT_JSON="$(cat "$ALERT_FILE")"
  RUNBOOK_URL="$(sed -n 's/.*"runbook_url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$ALERT_FILE" | head -1)"
else
  # A page-class alert carrying a runbook, which is the case the first agent is
  # built for. Trimmed to the fields the prompt actually reads.
  RUNBOOK_URL="https://github.com/tidbcloud/runbooks/wiki/UnhealthyPod"
  ALERT_JSON=$(cat <<JSON
{
  "id": "$ALERT_ID",
  "state": "open",
  "attrs": {
    "alertname": "UnhealthyPod",
    "classification": "page",
    "cluster_id": "1379661944600000000",
    "cluster_name": "prod-analytics",
    "region": "us-west-2",
    "component": "kubernetes",
    "summary": "Pod tidb1234/db-pd-0 has been in a non-ready state for longer than 10 minutes.",
    "labels": {
      "alertname": "UnhealthyPod",
      "severity": "critical",
      "oncall_team": "dedicated_service",
      "namespace": "tidb1234",
      "pod": "db-pd-0"
    },
    "annotations": {
      "message": "Pod tidb1234/db-pd-0 has been in a non-ready state for longer than 10 minutes.",
      "runbook_url": "$RUNBOOK_URL"
    }
  }
}
JSON
  )
fi

PAYLOAD=$(cat <<JSON
{
  "alert_id": "$ALERT_ID",
  "run_id": $RUN_ID,
  "agent": "runbook-triage",
  "trigger_kind": "alert_created",
  "alert": $ALERT_JSON,
  "runbook_url": "$RUNBOOK_URL",
  "disclosure": "shown",
  "callback": {
    "url": "$SINK/api/v1/alertstore/alerts/$ALERT_ID/agent-runs/$RUN_ID"
  }
}
JSON
)

echo "→ POST $ADAPTER/dispatch  ($ALERT_ID)"
curl -sS -X POST "$ADAPTER/dispatch" -H 'Content-Type: application/json' -d "$PAYLOAD"
echo
echo
echo "Watch the session in usher, and the sink for what the agent reports back."
