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

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

Reads dedicatedK8sResources JSON from stdin and formats it for display.

Expected schema (DevOps success envelope + business fields):
  {
    "errcode": 0,
    "content_type": "TEXT"|"YAML"|...,
    "content": "...",
    "truncated": false,
    "hints": "",
    "item_count": 0
  }

Behavior:
  - Prints meta: content_type, item_count, truncated, hints (if non-empty).
  - Prints content as-is in a markdown code fence (no YAML/TEXT parsing).
  - Fails if top-level "content" is missing.

Example:
  devops_http.sh --env dev --method POST \
    --path /cluster/dedicatedK8sResources \
    --query "cluster_id=123" --body '{...}' \
    --header "X-Request-ID: k8s-resource" \
  | format-k8s-resources.sh
EOF
}

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

input="$(cat)"

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

content_type="$(echo "$input" | jq -r '.content_type // empty')"
item_count="$(echo "$input" | jq -r '.item_count // empty')"
truncated="$(echo "$input" | jq -r '.truncated // false')"
hints="$(echo "$input" | jq -r '.hints // empty')"
content="$(echo "$input" | jq -r '.content')"
errcode="$(echo "$input" | jq -r '.errcode // empty')"
errmsg="$(echo "$input" | jq -r '.errmsg // empty')"

printf '### Dedicated K8s Resources\n\n'

if [ -n "$errcode" ]; then
  printf 'errcode: %s\n' "$errcode"
fi
if [ -n "$errmsg" ] && [ "$errmsg" != "null" ]; then
  printf 'errmsg: %s\n' "$errmsg"
fi
if [ -n "$content_type" ]; then
  printf 'content_type: %s\n' "$content_type"
fi
if [ -n "$item_count" ] && [ "$item_count" != "null" ]; then
  printf 'item_count: %s\n' "$item_count"
fi
printf 'truncated: %s\n' "$truncated"
if [ -n "$hints" ] && [ "$hints" != "null" ]; then
  printf 'hints: %s\n' "$hints"
fi
printf '\n'
printf '```\n%s\n```\n' "$content"
