#!/usr/bin/env bash
#
# jira-attach.sh  -  upload one or more files as Jira issue attachments and print
# the filename plus the URL of each, one per line, tab-separated.
#
# Two callers need this, and they share it rather than each carrying a curl: the issue
# generator (`generate-issue.md` step 12) and visual evidence (Phase 3 / Phase 5
# captures rendered into the Phase 5 Jira comment). Two copies of an upload is
# two places for the `X-Atlassian-Token: no-check` header to go missing, which
# fails as a 403 that reads like an auth problem.
#
# Usage:
#   jira-attach.sh <issue-key> <file> [file...]
#
# Env:
#   JIRA_BASE        https://host  -  names which account to use, when more than
#                    one is configured. Otherwise the account resolver picks.
#   JIRA_TOKEN_KEY   a store item name, when the account is to be named by item.
#   JIRA_TOKEN       a token for a run with no configured account.
#
# Output (stdout), one line per uploaded file:
#   <filename>\t<content-url>
#
# Exit: 0 all uploaded, 2 usage/environment, 3 an upload failed (partial uploads
# are reported on stdout before the failure, so a caller can still cite them).
set -uo pipefail

ISSUE="${1:-}"
shift 2>/dev/null || true
[ -n "$ISSUE" ] && [ "$#" -gt 0 ] || {
  echo "usage: jira-attach.sh <issue-key> <file> [file...]" >&2
  exit 2
}

_MA_JA_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
if [ -f "$_MA_JA_HERE/../lib/user-facing.sh" ]; then . "$_MA_JA_HERE/../lib/user-facing.sh"; else . "$HOME/.claude/lib/user-facing.sh"; fi
# shellcheck source=/dev/null
if [ -f "$_MA_JA_HERE/../lib/_service-account.sh" ]; then . "$_MA_JA_HERE/../lib/_service-account.sh"; else . "$HOME/.claude/lib/_service-account.sh"; fi

SA_PICK=()
if [ -n "${JIRA_BASE:-}" ]; then SA_PICK+=(--host "$JIRA_BASE"); fi
if [ -n "${JIRA_TOKEN_KEY:-}" ]; then SA_PICK+=(--item "$JIRA_TOKEN_KEY"); fi

JIRA_BASE="$(sa_base jira "${SA_PICK[@]+"${SA_PICK[@]}"}")" || {
  echo "jira-attach: $(sa_explain)" >&2
  exit 2
}
[ -n "$JIRA_BASE" ] || { echo "jira-attach: no Jira account  -  add one with $(ma_command setup)" >&2; exit 2; }

RC=0
for f in "$@"; do
  if [ ! -f "$f" ]; then
    echo "jira-attach: no such file: $f" >&2
    RC=3
    continue
  fi
  # The config carries the URL as well as the credential, so the two cannot be
  # separated: a redirect is refused rather than followed with the header on.
  cfg=$(sa_cfg jira "$JIRA_BASE/rest/api/2/issue/$ISSUE/attachments" bearer \
    "${SA_PICK[@]+"${SA_PICK[@]}"}") || {
    echo "jira-attach: $(sa_explain)" >&2
    exit 2
  }
  resp=$(curl -sS -X POST --config "$cfg" \
    -H "X-Atlassian-Token: no-check" \
    -F "file=@$f" 2>/dev/null)
  line=$(printf '%s' "$resp" | node -e '
    let b="";process.stdin.on("data",d=>b+=d).on("end",()=>{
      try{
        const j=JSON.parse(b);
        const a=Array.isArray(j)?j[0]:null;
        if(a&&a.filename&&a.content){process.stdout.write(a.filename+"\t"+a.content);return}
      }catch{}
      process.exit(1);
    })' 2>/dev/null)
  if [ -n "$line" ]; then
    printf '%s\n' "$line"
  else
    echo "jira-attach: upload failed for $(basename "$f")  -  $(printf '%s' "$resp" | head -c 200)" >&2
    RC=3
  fi
done
exit "$RC"
