#!/usr/bin/env bash
set -euo pipefail

# Register session ID → Claude Code PID mapping for kill-switch CLI lookup.
_FT_PIDS_DIR="${HOME}/.fewtok/state/session-pids"
mkdir -p "${_FT_PIDS_DIR}"
{
  _ft_pid=$$
  while [ -n "${_ft_pid:-}" ] && [ "${_ft_pid:-0}" -gt 1 ]; do
    _ft_comm=$(ps -o comm= -p "$_ft_pid" 2>/dev/null | tr -d ' ')
    if [ "$_ft_comm" = "claude" ] || [ "$_ft_comm" = "node" ]; then
      if [ -n "${CLAUDE_SESSION_ID:-}" ]; then
        printf '%s' "${CLAUDE_SESSION_ID}" > "${_FT_PIDS_DIR}/${_ft_pid}"
      fi
      break
    fi
    _ft_pid=$(ps -o ppid= -p "$_ft_pid" 2>/dev/null | tr -d ' ')
  done
} || true

is_fewtok_active() {
  [[ "${ANTHROPIC_BASE_URL:-}" =~ ^https?://(127\.|localhost|0\.0\.0\.0) ]] && return 0
  return 1
}

emit() {
  local s="$1"
  s="${s//\\/\\\\}"; s="${s//\"/\\\"}"; s="${s//$'\n'/\\n}"
  s="${s//$'\t'/\\t}"; s="${s//$'\r'/\\r}"
  printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}\n' "$s"
}

if is_fewtok_active; then
  emit "fewtok proxy active. Bash output compressed at API layer. Use Bash for ALL commands — build, test, lint, grep, find, everything. No output size concern."
fi
