#!/usr/bin/env bash
#
# jira-search.sh  -  run one JQL query and print Jira's own JSON.
#
# A thin front door onto `jira_search` in lib/issue-fetcher.sh, which owns the
# credential resolution, the host lookup and the rule that a token never reaches
# argv. This file adds exactly two things that function does not do for itself:
# it resolves the account from preferences, and it URL-encodes the query
# parameters (the JQL, the field list and the result cap).
#
# The encoding is not a detail. A JQL carrying a quoted label, a space or an
# `=` reaches the server mangled otherwise, and the failure is a 400 that reads
# like a permissions problem. python3 does it correctly; the shell does not.
#
# Usage:
#   jira-search.sh --jql '<JQL>' [--fields key,summary,priority,created] [--max 50]
#
# Exit: 0 with JSON on stdout, 1 when the query failed (a warning on stderr,
# never a token).

set -uo pipefail

JQL=""
FIELDS="key,summary,status,priority,created"
MAXR=50
while [ $# -gt 0 ]; do
  case "$1" in
    --jql) JQL="${2:-}"; shift 2 ;;
    --fields) FIELDS="${2:-}"; shift 2 ;;
    --max) MAXR="${2:-}"; shift 2 ;;
    -h | --help) grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'; exit 0 ;;
    *) echo "jira-search: unknown option $1" >&2; exit 2 ;;
  esac
done
[ -n "$JQL" ] || { echo "jira-search: --jql is required" >&2; exit 2; }

PREFS="${MA_PREFS_FILE:-$HOME/.claude/multi-agent-preferences.json}"
[ -f "$PREFS" ] || { echo "jira-search: no preferences file" >&2; exit 1; }

# Host and the LOGICAL key name, never the literal Keychain service name: the
# mapping is per-user and resolving it here is what keeps the service name out
# of every synced file.
eval "$(python3 - "$PREFS" <<'PY'
import json, sys, shlex
try:
    g = json.load(open(sys.argv[1]))["global"]
except Exception:
    g = {}
host = (g.get("hosts") or {}).get("jira", "")
key = (g.get("keychainMapping") or {}).get("jira", "")
print(f"ACCOUNT_JIRA_HOST={shlex.quote(host)}")
print(f"ACCOUNT_JIRA_TOKEN_KEY={shlex.quote(key)}")
PY
)"
export ACCOUNT_JIRA_HOST ACCOUNT_JIRA_TOKEN_KEY
[ -n "$ACCOUNT_JIRA_HOST" ] && [ -n "$ACCOUNT_JIRA_TOKEN_KEY" ] || {
  echo "jira-search: jira is not onboarded (host or keychainMapping.jira missing)" >&2
  exit 1
}

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
for cand in "$HERE/../lib/issue-fetcher.sh" "$HOME/.claude/lib/issue-fetcher.sh"; do
  [ -f "$cand" ] && { . "$cand"; break; }
done
command -v jira_search >/dev/null 2>&1 || {
  echo "jira-search: issue-fetcher.sh not found" >&2
  exit 1
}

urlq() { printf '%s' "$1" | python3 -c 'import sys,urllib.parse; print(urllib.parse.quote(sys.stdin.read(), safe=sys.argv[1]))' "$2"; }
jira_search "$(urlq "$JQL" /)" "$(urlq "$FIELDS" ,)" "$(urlq "$MAXR" "")"
