#!/bin/sh
# Claude Code SessionStart hook for Agentic Traffic Control.
#
# SessionStart only runs command hooks, so this forwards the hook payload to the tower with
# curl, and saves the session id to $CLAUDE_ENV_FILE as ATC_SESSION_ID so that `atc-emit`
# (run later from the agent's Bash tool) reports as the same agent.
#
# It never fails the session: no token, no network or a slow server all exit 0 quietly.
ATC_URL="${ATC_URL:-https://agentictrafficcontrol.com}"
payload=$(cat)

session_id=$(printf '%s' "$payload" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
if [ -n "${CLAUDE_ENV_FILE:-}" ]; then
  [ -n "$session_id" ] && printf 'export ATC_SESSION_ID=%s\n' "$session_id" >> "$CLAUDE_ENV_FILE"
  # So the skill can run `sh "$ATC_EMIT" ...` from any directory.
  emit="$(cd "$(dirname "$0")" && pwd)/atc-emit"
  printf "export ATC_EMIT='%s'\n" "$emit" >> "$CLAUDE_ENV_FILE"
fi

[ -n "${ATC_TOKEN:-}" ] || exit 0
printf '%s' "$payload" | curl -s -m 4 -o /dev/null -X POST \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ATC_TOKEN" \
  -H "X-ATC-Ticket: ${ATC_TICKET:-}" \
  -H "X-ATC-Runtime: ${ATC_RUNTIME:-}" \
  --data-binary @- "$ATC_URL/v1/hooks/claude" || true
exit 0
