#!/usr/bin/env bash
# Run one Claude Code prompt with claude -p and print the JSON result field.
#
# Copy this file to scripts/claude-headless.sh. The workflow in this folder
# calls it from there.
#
# Auth, from the Claude Code authentication docs (checked November 1, 2026):
#   ANTHROPIC_API_KEY          API key. In -p mode the key is used when set.
#   CLAUDE_CODE_OAUTH_TOKEN    Subscription token from `claude setup-token`.
# --bare does not read the subscription token. This script passes --bare only
# when ANTHROPIC_API_KEY is set. If both are set, the API key path wins.
#
# --from-json reads a file instead of calling claude. documented-result.json
# is the documented shape, not a live run. No model was called to test this file.
set -euo pipefail

usage() {
  printf '%s\n' \
    'Usage: claude-headless.sh "prompt"' \
    '       claude-headless.sh --from-json path/to/result.json' >&2
}

from_json=''
prompt=''

if [[ ${1:-} == '--from-json' ]]; then
  from_json=${2:-}
  if [[ -z ${from_json} || ! -f ${from_json} ]]; then
    usage
    exit 2
  fi
elif [[ $# -eq 1 && -n ${1} ]]; then
  prompt=$1
else
  usage
  exit 2
fi

if ! command -v jq >/dev/null 2>&1; then
  printf '%s\n' 'jq is required to read the result field.' >&2
  exit 2
fi

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

if [[ -n ${from_json} ]]; then
  cp -- "${from_json}" "${tmp}"
else
  if ! command -v claude >/dev/null 2>&1; then
    printf '%s\n' 'claude is not on PATH. Install @anthropic-ai/claude-code first.' >&2
    exit 2
  fi
  if [[ -z ${ANTHROPIC_API_KEY:-} && -z ${CLAUDE_CODE_OAUTH_TOKEN:-} ]]; then
    printf '%s\n' 'Set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN. This script does not log in.' >&2
    exit 2
  fi

  if [[ -n ${ANTHROPIC_API_KEY:-} ]]; then
    claude --bare -p "${prompt}" \
      --output-format json \
      --permission-mode dontAsk \
      --allowedTools 'Read' >"${tmp}"
  else
    claude -p "${prompt}" \
      --output-format json \
      --permission-mode dontAsk \
      --allowedTools 'Read' >"${tmp}"
  fi
fi

jq -e 'has("result") and (.result | type == "string")' "${tmp}" >/dev/null
printf 'session_id %s\n' "$(jq -r '.session_id // empty' "${tmp}")" >&2
printf 'total_cost_usd %s\n' "$(jq -r 'if has("total_cost_usd") then (.total_cost_usd | tostring) else empty end' "${tmp}")" >&2
jq -r '.result' "${tmp}"
