#!/usr/bin/env bash
# fetch-jira-sprint-issues.sh — Fetch sprint issues from Jira REST API.
#
# Primary Jira data source for sprint reports.
# Outputs a JSON object with an "issues" array.
# Handles pagination automatically (nextPageToken).
#
# Usage:
#   ./fetch-jira-sprint-issues.sh --project SQSH
#   ./fetch-jira-sprint-issues.sh --project SQSH --sprint "Shark 60"
#
# Requires:
#   JIRA_EMAIL     (or ATLASSIAN_EMAIL, JIRA_USERNAME, JIRA_USER)
#   JIRA_API_TOKEN (or ATLASSIAN_API_TOKEN, JIRA_TOKEN)
#
# Optional:
#   JIRA_BASE_URL  (default: https://humand.atlassian.net)
#
# Output: JSON object with "issues" array and "total" count to stdout.

set -euo pipefail

usage() {
  echo "Usage: $0 --project <KEY> [--sprint '<NAME>']" >&2
  exit 1
}

PROJECT=""
SPRINT=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --project) PROJECT="$2"; shift 2 ;;
    --sprint)  SPRINT="$2";  shift 2 ;;
    -h|--help) usage ;;
    *) echo "Unknown arg: $1" >&2; usage ;;
  esac
done

[[ -z "$PROJECT" ]] && { echo "Error: --project is required" >&2; usage; }

BASE="${JIRA_BASE_URL:-${ATLASSIAN_BASE_URL:-https://humand.atlassian.net}}"
BASE="${BASE%/}"
[[ "$BASE" == */browse ]] && BASE="${BASE%/browse}"

EMAIL="${JIRA_EMAIL:-${ATLASSIAN_EMAIL:-${JIRA_USERNAME:-${JIRA_USER:-}}}}"
TOKEN="${JIRA_API_TOKEN:-${ATLASSIAN_API_TOKEN:-${JIRA_TOKEN:-}}}"

if [[ -z "$EMAIL" || -z "$TOKEN" ]]; then
  echo "Error: Jira credentials missing. Set JIRA_EMAIL + JIRA_API_TOKEN." >&2
  exit 2
fi

if [[ -n "$SPRINT" ]]; then
  JQL="sprint = \"${SPRINT}\" AND project = \"${PROJECT}\" ORDER BY status ASC, priority DESC"
else
  JQL="sprint in openSprints() AND project = \"${PROJECT}\" ORDER BY status ASC, priority DESC"
fi

FIELDS="summary,issuetype,status,priority,assignee,parent,customfield_10020,customfield_10021,customfield_10028,customfield_10000,customfield_10097"

all_issues="[]"
next_token=""
page=0

while true; do
  page=$((page + 1))

  extra_args=()
  if [[ -n "$next_token" ]]; then
    extra_args+=(--data-urlencode "nextPageToken=${next_token}")
  fi

  response=$(curl -sS -w "\n%{http_code}" \
    -u "${EMAIL}:${TOKEN}" \
    -H "Accept: application/json" \
    --get "${BASE}/rest/api/3/search/jql" \
    --data-urlencode "jql=${JQL}" \
    --data-urlencode "maxResults=100" \
    --data-urlencode "fields=${FIELDS}" \
    "${extra_args[@]+"${extra_args[@]}"}" \
    2>/dev/null)

  http_code=$(echo "$response" | tail -1)
  body=$(echo "$response" | sed '$d')

  if [[ "$http_code" != "200" ]]; then
    echo "Error: Jira API returned HTTP $http_code (page $page)" >&2
    echo "$body" >&2
    exit 3
  fi

  read -r count is_last token < <(echo "$body" | python3 -c "
import json, sys
d = json.load(sys.stdin)
issues = d.get('issues', [])
print(len(issues), str(d.get('isLast', True)).lower(), d.get('nextPageToken', ''))
")

  all_issues=$(echo "$body" | python3 -c "
import json, sys
existing = json.loads(sys.argv[1])
new_page = json.load(sys.stdin).get('issues', [])
existing.extend(new_page)
print(json.dumps(existing))
" "$all_issues")

  echo "Fetched page $page ($count issues)" >&2

  if [[ "$is_last" == "true" ]] || [[ -z "$token" ]]; then
    break
  fi
  next_token="$token"
done

echo "$all_issues" | python3 -c "
import json, sys
issues = json.load(sys.stdin)
print(json.dumps({'issues': issues, 'total': len(issues)}, indent=2))
"
