#!/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 used to carry their own curl: the issue
# generator (`generate-issue.md` step 12) and visual evidence (Phase 3 / Phase 5
# captures rendered into the Phase 7 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  -  else resolved from prefs hosts.jira
#   JIRA_TOKEN       else resolved from prefs keychainMapping.jira
#
# 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
}

PREFS="$HOME/.claude/multi-agent-preferences.json"

if [ -z "${JIRA_BASE:-}" ]; then
  JIRA_BASE=$(node -e '
    const fs=require("fs");
    try{const g=(JSON.parse(fs.readFileSync(process.argv[1],"utf8")).global||{});
        process.stdout.write((g.hosts||{}).jira||"")}catch{process.stdout.write("")}
  ' "$PREFS" 2>/dev/null)
fi
[ -n "$JIRA_BASE" ] || { echo "jira-attach: no Jira host (set JIRA_BASE or prefs hosts.jira)" >&2; exit 2; }
case "$JIRA_BASE" in http*) ;; *) JIRA_BASE="https://$JIRA_BASE" ;; esac

if [ -z "${JIRA_TOKEN:-}" ]; then
  KEY=$(node -e '
    const fs=require("fs");
    try{const g=(JSON.parse(fs.readFileSync(process.argv[1],"utf8")).global||{});
        process.stdout.write((g.keychainMapping||{}).jira||"")}catch{process.stdout.write("")}
  ' "$PREFS" 2>/dev/null)
  [ -n "$KEY" ] || { echo "jira-attach: keychainMapping.jira is not set  -  onboard it via /multi-agent:setup" >&2; exit 2; }
  JIRA_TOKEN=$(bash "$HOME/.claude/lib/credential-store.sh" get "$KEY" 2>/dev/null)
fi
[ -n "${JIRA_TOKEN:-}" ] || { echo "jira-attach: no Jira token  -  onboard it via /multi-agent: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 token never reaches argv: curl reads the header from a file descriptor.
  resp=$(curl -sS -X POST \
    -H @<(printf 'Authorization: Bearer %s\n' "$JIRA_TOKEN") \
    -H "X-Atlassian-Token: no-check" \
    -F "file=@$f" \
    "$JIRA_BASE/rest/api/2/issue/$ISSUE/attachments" 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"
