#!/usr/bin/env bash
# Task 560 — emitter library writes one well-formed JSON record per call,
# truncates oversize stderr, and emits an observability line to server.log.
set -u

LIB="$(cd "$(dirname "$0")/.." && pwd)/lib/hook-emit.sh"
[[ -f "$LIB" ]] || { echo "FAIL: $LIB missing"; exit 1; }

TMPDIR_OVERRIDE=$(mktemp -d)
export MAXY_HOOK_BUFFER_DIR="$TMPDIR_OVERRIDE/buffers"
export MAXY_HOOK_SERVER_LOG="$TMPDIR_OVERRIDE/server.log"
mkdir -p "$MAXY_HOOK_BUFFER_DIR"

PASS=0; FAIL=0
pass() { PASS=$((PASS+1)); echo "PASS: $1"; }
fail() { FAIL=$((FAIL+1)); echo "FAIL: $1" >&2; }

# shellcheck disable=SC1090
source "$LIB" || { fail "source library"; exit 1; }
pass "source library"

# Test 1: one call writes one well-formed JSON record keyed by session id.
SESSION_ID="abc-123-def"
hook_emit_decision \
  "$SESSION_ID" \
  "admin-tool-gate" \
  "Bash" \
  "block" \
  "orchestration-only" \
  "Blocked: Bash is not callable from admin." \
  2 \
  10
BUFFER="$MAXY_HOOK_BUFFER_DIR/$SESSION_ID.jsonl"
if [[ ! -f "$BUFFER" ]]; then
  fail "buffer file not created at $BUFFER"
else
  LINES=$(wc -l <"$BUFFER" | tr -d ' ')
  [[ "$LINES" -eq 1 ]] && pass "one record per call" || fail "expected 1 line, got $LINES"
  for key in agentId hookName toolName decision reason stderr exitCode durationMs truncated ts; do
    if python3 -c "import json,sys; d=json.loads(open(sys.argv[1]).read().strip()); sys.exit(0 if '$key' in d else 1)" "$BUFFER"; then
      pass "record carries $key"
    else
      fail "record missing $key"
    fi
  done
fi

# Test 2: oversize stderr is truncated to ~4 KB with truncated=true.
BIG=$(python3 -c 'print("X"*40000)')
hook_emit_decision \
  "$SESSION_ID" \
  "noisy-hook" \
  "Bash" \
  "block" \
  "synthetic" \
  "$BIG" \
  2 \
  5
TAIL_REC=$(tail -1 "$BUFFER")
TRUNC=$(echo "$TAIL_REC" | python3 -c 'import json,sys; print(json.loads(sys.stdin.read())["truncated"])')
[[ "$TRUNC" == "True" ]] && pass "oversize record marked truncated" || fail "oversize record not marked truncated (got $TRUNC)"
LEN=$(echo "$TAIL_REC" | python3 -c 'import json,sys; print(len(json.loads(sys.stdin.read())["stderr"]))')
[[ "$LEN" -le 4200 ]] && pass "stderr clipped to bound (len=$LEN)" || fail "stderr not clipped (len=$LEN)"

# Test 3: server.log observability line emitted.
if grep -q '\[hook-propagate\] ' "$MAXY_HOOK_SERVER_LOG"; then
  pass "server.log got [hook-propagate] line"
else
  fail "server.log missing [hook-propagate] line"
fi

rm -rf "$TMPDIR_OVERRIDE"
echo "----"
echo "$PASS pass, $FAIL fail"
[[ "$FAIL" -eq 0 ]]
