#!/usr/bin/env bash
# Fetches a single Jira issue (fields=*all, rendered HTML description, field-name map)
# and writes the raw API response as JSON.
#
# Usage: jira-fetch-issue.sh <ISSUE-KEY> <OUTPUT-JSON-PATH>
#
# Requires:
#   JIRA_CREDENTIALS  "email@example.com:api-token" (Basic auth, same as this org's Jira client)
#   JIRA_BASE_URL     optional, defaults to https://ksense-tech.atlassian.net

set -euo pipefail

usage() {
  echo "Usage: $(basename "$0") <ISSUE-KEY> <OUTPUT-JSON-PATH>" >&2
  exit 1
}

[ $# -eq 2 ] || usage

KEY="$1"
OUT="$2"

: "${JIRA_BASE_URL:=https://ksense-tech.atlassian.net}"
JIRA_BASE_URL="${JIRA_BASE_URL%/}"

if [ -z "${JIRA_CREDENTIALS:-}" ]; then
  echo "JIRA_CREDENTIALS is not set. Export it as 'email@example.com:api-token' and retry." >&2
  exit 1
fi

command -v curl >/dev/null 2>&1 || { echo "curl is required" >&2; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 1; }

AUTH="$(printf '%s' "$JIRA_CREDENTIALS" | base64 -w0)"

TMP="${OUT}.tmp"
HTTP_STATUS="$(curl -sS -o "$TMP" -w '%{http_code}' \
  -H "Authorization: Basic ${AUTH}" \
  -H "Accept: application/json" \
  "${JIRA_BASE_URL}/rest/api/3/issue/${KEY}?fields=*all&expand=renderedFields,names")"

if [ "$HTTP_STATUS" != "200" ]; then
  echo "Jira API request for ${KEY} failed with HTTP ${HTTP_STATUS}:" >&2
  cat "$TMP" >&2
  rm -f "$TMP"
  exit 1
fi

if ! jq empty "$TMP" 2>/dev/null; then
  echo "Jira API response for ${KEY} was not valid JSON:" >&2
  cat "$TMP" >&2
  rm -f "$TMP"
  exit 1
fi

mkdir -p "$(dirname "$OUT")"
mv "$TMP" "$OUT"
echo "Wrote ${OUT}"
