#!/usr/bin/env bash
#
# overlay-telemetry.sh — BALDART PostToolUse hook (matcher: Read).
#
# OBSERVATION ONLY. Appends one JSON line to
# `.baldart/telemetry/overlay-loads.jsonl` every time a `.baldart/overlays/*.md`
# file is read. This is the *numerator* of the overlay-load question: when the
# agent runs a skill that HAS an overlay, does it actually load it? A `Read` of
# the overlay file is the one objective signal — skill self-report would be
# corrupted in exactly the case we measure ("the agent forgot the overlay").
#
# Bash, NOT node, on purpose: this fires on EVERY `Read` (the hottest tool) in
# the consumer's critical path. A per-read node cold-start (~50ms) would tax
# every file read; a bash fork (~5ms) keeps the hot path cheap. The work is just
# a path match + a conditional append, so bash is sufficient. Same precedent as
# agent-discovery-info.sh.
#
# Numerator-only by design — skill invocation is prompt-expansion, not a tool
# call, so the denominator is not hook-observable (claude-code #43630, #22655).
# See framework/docs/OVERLAY-TELEMETRY.md for the under-count caveats.
#
# Fail-safe: always exit 0, never disrupt the session.

set -u
exec 2>/dev/null  # never surface stderr to the user

INPUT=""
if [ ! -t 0 ]; then
  INPUT="$(cat)"
fi
[ -z "$INPUT" ] && exit 0

get_field() {
  # $1 = JSON key (top-level or nested — sed fallback matches anywhere)
  if command -v jq >/dev/null 2>&1; then
    printf '%s' "$INPUT" | jq -r "$2 // empty" 2>/dev/null
  else
    printf '%s' "$INPUT" | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" | head -1
  fi
}

TOOL_NAME="$(get_field tool_name '.tool_name')"
[ "$TOOL_NAME" = "Read" ] || exit 0

FILE_PATH="$(get_field file_path '.tool_input.file_path')"
[ -n "$FILE_PATH" ] || exit 0

CWD="$(get_field cwd '.cwd')"
[ -n "$CWD" ] || CWD="$PWD"
SESSION_ID="$(get_field session_id '.session_id')"

# Resolve relative paths against cwd.
case "$FILE_PATH" in
  /*) ABS="$FILE_PATH" ;;
  *)  ABS="$CWD/$FILE_PATH" ;;
esac

# Must live under .baldart/overlays/.
case "$ABS" in
  */.baldart/overlays/*) ;;
  *) exit 0 ;;
esac
REL="${ABS##*/.baldart/overlays/}"   # everything after the last marker

# Classify — mirror src/utils/overlay-merger / overlay.js path logic.
# Order matters: deeper/excluded patterns before the catch-alls.
KIND=""
NAME=""
case "$REL" in
  *.example.md) exit 0 ;;
  README.md) exit 0 ;;
  */*/*) exit 0 ;;                                                       # 3+ levels — ignore
  agents/*.md)   KIND="agent";   NAME="${REL#agents/}";   NAME="${NAME%.md}" ;;
  commands/*.md) KIND="command"; NAME="${REL#commands/}"; NAME="${NAME%.md}" ;;
  */*) exit 0 ;;                                                         # 2 levels, not agents/commands — ignore
  *.md) KIND="skill"; NAME="${REL%.md}" ;;
  *) exit 0 ;;
esac
[ -n "$KIND" ] && [ -n "$NAME" ] || exit 0

TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
if [ -n "$SESSION_ID" ]; then SID="\"$SESSION_ID\""; else SID="null"; fi

mkdir -p "$CWD/.baldart/telemetry" || exit 0
printf '{"ts":"%s","event":"overlay-read","kind":"%s","name":"%s","session_id":%s}\n' \
  "$TS" "$KIND" "$NAME" "$SID" >> "$CWD/.baldart/telemetry/overlay-loads.jsonl"

exit 0
