# shellcheck shell=sh
# Render one catalogue message (AD-34) in the envelope a hook platform
# expects (CAP-11, Deep Dive 2026-09-03). Usage:
#
#   hook-context.sh <format> <key>
#
# Formats:
#   plain    the message text as is -- Codex UserPromptSubmit and Kiro
#            PromptSubmit add plain stdout to the model's context
#   copilot  {"additionalContext": "<text>"} -- Copilot sessionStart
#   gemini   {"hookSpecificOutput": {"hookEventName": "BeforeAgent",
#            "additionalContext": "<text>"}} -- Gemini CLI BeforeAgent
#
# The seed that names this script carries a KEY, never a sentence: seeds
# are never overwritten, this script and the catalogue are owned
# artifacts replaced on every install. Prints nothing when the key or
# the catalogue is missing -- no context beats a stale instruction.

set -u
[ "$#" -ge 2 ] || exit 0
format_="$1"
catalogue_="$(dirname "$0")/messages.txt"
[ -r "${catalogue_}" ] || exit 0
text_="$(LC_ALL=C awk -F'\t' -v k="$2" '$1==k {printf "%s", $2; exit}' "${catalogue_}" 2>/dev/null)"
[ -n "${text_}" ] || exit 0

json_escape() {
  # Backslash and double quote are the only characters the catalogue
  # may carry that need escaping; tabs cannot appear (they separate
  # key and text) and newlines end the entry.
  printf '%s' "$1" | LC_ALL=C sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

case "${format_}" in
  plain)
    printf '%s\n' "${text_}"
    ;;
  copilot)
    printf '{"additionalContext": "%s"}\n' "$(json_escape "${text_}")"
    ;;
  gemini)
    printf '{"hookSpecificOutput": {"hookEventName": "BeforeAgent", "additionalContext": "%s"}}\n' \
      "$(json_escape "${text_}")"
    ;;
  *)
    exit 0
    ;;
esac
exit 0
