#!/bin/bash
# AgentPin bridge: forwards Claude Code hook events to the AgentPin panel.
# It never gets in Claude Code's way: if AgentPin isn't running, it exits silently
# and Claude Code carries on exactly as it would without it.
EVENT="${1:-unknown}"
DIR="$HOME/Library/Application Support/AgentPin"
TOKEN="$(cat "$DIR/token" 2>/dev/null)" || exit 0
[ -n "$TOKEN" ] || exit 0
PORT="$(cat "$DIR/port" 2>/dev/null)"
URL="http://127.0.0.1:${PORT:-47321}/hook"
# Tells the panel which app this session lives in, so it can label it and bring it forward.
HOST="${__CFBundleIdentifier:-}"
ENTRY="${CLAUDE_CODE_ENTRYPOINT:-}"

if [ "$EVENT" = "PreToolUse" ]; then
  # Runs before every step. The status update goes out in the background, so it never slows Claude.
  input="$(cat)"
  printf '%s' "$input" | curl -s --connect-timeout 1 --max-time 4 \
    -H 'Expect:' -H 'Content-Type: application/json' -H "X-AgentPin-Token: $TOKEN" \
    -H "X-AgentPin-Host: $HOST" -H "X-AgentPin-Entry: $ENTRY" \
    --data-binary @- "$URL" >/dev/null 2>&1 &
  # Paused from the pin: hold here, before the step, until you resume it. AgentPin keeps one
  # file per paused session. Fails open: if AgentPin quits, the agent carries on.
  P="$DIR/paused"
  if [ -d "$P" ] && [ -n "$(ls -A "$P" 2>/dev/null)" ]; then
    SID="$(printf '%s' "$input" | grep -o '"session_id" *: *"[^"]*"' | head -1 | sed 's/.*"\([^"]*\)"$/\1/')"
    n=0
    while [ -n "$SID" ] && [ -e "$P/$SID" ]; do
      sleep 1
      n=$((n + 1))
      if [ $((n % 3)) -eq 0 ]; then
        curl -s --fail --connect-timeout 1 --max-time 2 "http://127.0.0.1:${PORT:-47321}/health" >/dev/null 2>&1 || break
      fi
    done
  fi
  exit 0
fi

if [ "$EVENT" = "PermissionRequest" ]; then
  # Blocks until you click Allow / Deny in the panel. Empty reply = ask in the terminal as usual.
  out="$(curl -s --fail --connect-timeout 1 --max-time 590 \
    -H 'Expect:' -H 'Content-Type: application/json' -H "X-AgentPin-Token: $TOKEN" \
    -H "X-AgentPin-Host: $HOST" -H "X-AgentPin-Entry: $ENTRY" \
    --data-binary @- "$URL" 2>/dev/null)" || exit 0
  [ -n "$out" ] && printf '%s\n' "$out"
else
  curl -s --connect-timeout 1 --max-time 4 \
    -H 'Expect:' -H 'Content-Type: application/json' -H "X-AgentPin-Token: $TOKEN" \
    -H "X-AgentPin-Host: $HOST" -H "X-AgentPin-Entry: $ENTRY" \
    --data-binary @- "$URL" >/dev/null 2>&1
fi
exit 0
