#!/usr/bin/env bash
# SessionStart hook for the drogon plugin - injects CLAUDE.md rules as
# additionalContext. Pure shell on purpose: no interpreter dependency, so it
# runs identically on Windows (Git Bash), Linux and macOS, in both Claude Code
# and ZCode. Protocol: read JSON event from stdin (ignored), write a single
# JSON object to stdout, diagnostics to stderr only.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Host-provided plugin root wins; fall back to the script location so the hook
# also works when neither CLAUDE_PLUGIN_ROOT nor ZCODE_PLUGIN_ROOT is exported.
ROOT="${CLAUDE_PLUGIN_ROOT:-${ZCODE_PLUGIN_ROOT:-$PLUGIN_ROOT}}"
RULES="$ROOT/CLAUDE.md"

[ -f "$RULES" ] || exit 0

# Escape content for embedding as a JSON string value using bash parameter
# substitution (single pass each, no external process needed).
escape_for_json() {
    local s="$1"
    s="${s//\\/\\\\}"
    s="${s//\"/\\\"}"
    s="${s//$'\n'/\\n}"
    s="${s//$'\r'/\\r}"
    s="${s//$'\t'/\\t}"
    printf '%s' "$s"
}

# $(cat ...) drops trailing newlines, which is fine for a JSON string value.
content="$(cat "$RULES")"
[ -n "$content" ] || exit 0

# 剔除其余 C0 控制字符(保留 \t / \n / \r —— 它们随后会被转义)。
# 否则规则文件里若出现 \f、\v 等字符,产出的 JSON 不合法,宿主解析失败,
# 表现为"规则注入静默失效"。tr 随 bash 在 Git Bash / Linux / macOS 均可用。
# 注意:本脚本以 `set -euo pipefail` 运行,命令替换失败会让脚本以非零退出,
# 违反 "SessionStart 必须 exit 0" 的约定 —— 因此这里显式捕获失败并降级。
if command -v tr >/dev/null 2>&1; then
    if ! content="$(printf '%s' "$content" | LC_ALL=C tr -d '\000-\010\013\014\016-\037\177')"; then
        exit 0
    fi
else
    # 没有 tr 就无法保证 JSON 合法 —— 宁可跳过注入,也不要产出非法 JSON。
    exit 0
fi
[ -n "$content" ] || exit 0

printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}' \
    "$(escape_for_json "$content")"
