#!/bin/bash
# AgentDrop PostToolUse Hook — Inbox Notification
#
# Silently checks your AgentDrop inbox after every tool use.
# If NEW (unseen) transfers are waiting, notifies the agent via exit code 2.
# Transfers that have already been notified about are tracked and skipped.
#
# Install: Add to Claude Code settings.json under hooks.PostToolUse
# Requires: AGENTDROP_API_KEY and AGENTDROP_AGENT_ID env vars
#           (already set if you have the MCP server configured)

set -e

# ── Config ──────────────────────────────────────────────
API_BASE="${AGENTDROP_API_BASE:-https://api.agent-drop.com}"
CACHE_DIR="${TMPDIR:-/tmp}/agentdrop-hook-cache"
CACHE_FILE="$CACHE_DIR/last-check"
SEEN_FILE="$CACHE_DIR/seen-transfers"
CHECK_INTERVAL=30  # seconds between actual API calls

# ── Guard: skip if no credentials ───────────────────────
if [ -z "$AGENTDROP_API_KEY" ] || [ -z "$AGENTDROP_AGENT_ID" ]; then
  # Try loading from config file
  CONFIG_DIR="${AGENTDROP_CONFIG_DIR:-$HOME/.agentdrop}"
  CONFIG_FILE="$CONFIG_DIR/config.json"

  if [ -f "$CONFIG_FILE" ]; then
    # Extract from JSON (works without jq)
    if [ -z "$AGENTDROP_API_KEY" ]; then
      AGENTDROP_API_KEY=$(grep -o '"api_key"[[:space:]]*:[[:space:]]*"[^"]*"' "$CONFIG_FILE" | head -1 | sed 's/.*"api_key"[[:space:]]*:[[:space:]]*"//;s/"$//')
    fi
    if [ -z "$AGENTDROP_AGENT_ID" ]; then
      AGENTDROP_AGENT_ID=$(grep -o '"agent_id"[[:space:]]*:[[:space:]]*"[^"]*"' "$CONFIG_FILE" | head -1 | sed 's/.*"agent_id"[[:space:]]*:[[:space:]]*"//;s/"$//')
    fi
  fi

  # Still missing? Silent exit.
  if [ -z "$AGENTDROP_API_KEY" ] || [ -z "$AGENTDROP_AGENT_ID" ]; then
    exit 0
  fi
fi

# ── Throttle: skip if checked recently ──────────────────
mkdir -p "$CACHE_DIR" 2>/dev/null || true

if [ -f "$CACHE_FILE" ]; then
  LAST_CHECK=$(cat "$CACHE_FILE" 2>/dev/null || echo "0")
  NOW=$(date +%s)
  ELAPSED=$((NOW - LAST_CHECK))

  if [ "$ELAPSED" -lt "$CHECK_INTERVAL" ]; then
    # Checked recently, skip
    exit 0
  fi
fi

# ── Check inbox ─────────────────────────────────────────
# Update timestamp BEFORE the call (prevents parallel requests)
date +%s > "$CACHE_FILE" 2>/dev/null || true

RESPONSE=$(curl -s -m 5 -w "\n%{http_code}" \
  -H "Authorization: Bearer $AGENTDROP_API_KEY" \
  -H "X-Agent-ID: $AGENTDROP_AGENT_ID" \
  "$API_BASE/v1/transfers/inbox?status=active&limit=10" 2>/dev/null) || exit 0

# Split response body and HTTP status
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')

# Non-200? Silent exit.
if [ "$HTTP_CODE" != "200" ]; then
  exit 0
fi

# ── Parse transfers and filter out already-seen ones ────
# Extract all transfer IDs from response
ALL_IDS=$(echo "$BODY" | grep -o '"id"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"id"[[:space:]]*:[[:space:]]*"//;s/"$//')

if [ -z "$ALL_IDS" ]; then
  exit 0
fi

# Load seen transfer IDs
touch "$SEEN_FILE" 2>/dev/null || true
SEEN=$(cat "$SEEN_FILE" 2>/dev/null || echo "")

# Filter to only NEW (unseen) transfer IDs
NEW_IDS=""
NEW_COUNT=0
for TID in $ALL_IDS; do
  if ! echo "$SEEN" | grep -qF "$TID"; then
    NEW_IDS="$NEW_IDS $TID"
    NEW_COUNT=$((NEW_COUNT + 1))
  fi
done

if [ "$NEW_COUNT" -gt "0" ]; then
  # Mark these as seen so we don't notify again
  for TID in $NEW_IDS; do
    echo "$TID" >> "$SEEN_FILE"
  done

  # Extract sender names for the new transfers
  SENDERS=$(echo "$BODY" | grep -o '"sender_display_name"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"sender_display_name"[[:space:]]*:[[:space:]]*"//;s/"$//' | sort -u | head -3)

  if [ -z "$SENDERS" ]; then
    SENDERS=$(echo "$BODY" | grep -o '"sender"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"sender"[[:space:]]*:[[:space:]]*"//;s/"$//' | sort -u | head -3)
  fi

  SENDER_LIST=$(echo "$SENDERS" | tr '\n' ', ' | sed 's/,$//')

  if [ "$NEW_COUNT" -eq "1" ]; then
    echo "You have 1 new file transfer in your AgentDrop inbox from ${SENDER_LIST}. Use check_inbox to see details and download_transfer to retrieve it." >&2
  else
    echo "You have ${NEW_COUNT} new file transfers in your AgentDrop inbox (from: ${SENDER_LIST}). Use check_inbox to see all transfers and download_transfer to retrieve them." >&2
  fi
  exit 2
fi

# All transfers already seen — silent success
exit 0
