#!/usr/bin/env bash
set -Eeuo pipefail

usage() {
  cat <<'EOF'
Usage:
  format-cluster-resources.sh

Reads cluster-resources JSON from stdin and formats it for display.

Expected schema:
  { "resources": [ { "key": "...", "display_name": "...",
    "description": "...", "type": "...", "content": "..." }, ... ] }

Known keys: cluster_cr, scale_status_cm (latter only when feature-enabled).

Behavior:
  - Resources with key == "cluster_cr" are listed first.
  - Each resource heading uses display_name; description follows.
  - Content is printed in a markdown code fence (jq -r unescapes JSON strings).
  - If no resource has key "cluster_cr", a warning line is printed at the end.

Example:
  devops_http.sh --env dev --path /clusters/123/cluster-resources \
    --header "X-Request-ID: cr-lookup" \
    | format-cluster-resources.sh
EOF
}

for arg in "$@"; do
  case "$arg" in
    -h|--help) usage; exit 0 ;;
    *) printf '[format-cluster-resources] unknown argument: %s\n' "$arg" >&2; exit 1 ;;
  esac
done

input="$(cat)"

if ! echo "$input" | jq -e '.resources' >/dev/null 2>&1; then
  printf '[format-cluster-resources] error: input JSON missing top-level ".resources" array\n' >&2
  exit 1
fi

has_cluster_cr="$(echo "$input" | jq '[.resources[] | select(.key == "cluster_cr")] | length')"

resources="$(echo "$input" | jq -c '
  .resources
  | sort_by(if .key == "cluster_cr" then 0 else 1 end)
')"

count="$(echo "$resources" | jq 'length')"

i=0
while [ "$i" -lt "$count" ]; do
  display_name="$(echo "$resources" | jq -r ".[$i].display_name")"
  description="$(echo "$resources" | jq -r ".[$i].description")"
  content="$(echo "$resources" | jq -r ".[$i].content")"

  printf '### %s\n' "$display_name"
  printf 'Description: %s\n\n' "$description"
  printf '```\n%s\n```\n\n' "$content"

  i=$((i + 1))
done

if [ "$has_cluster_cr" -eq 0 ]; then
  printf '⚠ **cluster_cr not found** in resources.\n'
fi
