#!/usr/bin/env bash
# SessionStart hook: Fetch policies from Clew Engine and cache locally.
#
# Reads CLEW_API_URL (default: http://localhost:8000/v1) and optional
# CLEW_API_KEY.  Writes policies to ~/.clew/policy-cache.json.
# Injects a policy summary into Claude's context.
#
# Exit codes: 0 = success, 1 = non-blocking error (fail-open)
set -euo pipefail

CLEW_API_URL="${CLEW_API_URL:-http://localhost:8000/v1}"
CACHE_DIR="$HOME/.clew"
CACHE_FILE="$CACHE_DIR/policy-cache.json"

mkdir -p "$CACHE_DIR"

# Build auth header
AUTH_HEADER=""
if [ -n "${CLEW_API_KEY:-}" ]; then
  AUTH_HEADER="-H Authorization: Bearer $CLEW_API_KEY"
fi

# Fetch policies with timeout
POLICIES=$(curl -sf --max-time 5 \
  ${AUTH_HEADER:+"$AUTH_HEADER"} \
  "$CLEW_API_URL/policies/export" 2>/dev/null) || {
  # API unreachable — write empty cache, fail open
  echo "[]" > "$CACHE_FILE"
  echo '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"Clew policy cache: API unreachable, running without policy enforcement."}}'
  exit 0
}

# Write cache
echo "$POLICIES" > "$CACHE_FILE"

# Count policies by severity
TOTAL=$(echo "$POLICIES" | jq 'length')
BLOCK_COUNT=$(echo "$POLICIES" | jq '[.[] | select(.severity == "block")] | length')
WARN_COUNT=$(echo "$POLICIES" | jq '[.[] | select(.severity == "warn")] | length')
AUDIT_COUNT=$(echo "$POLICIES" | jq '[.[] | select(.severity == "audit")] | length')

if [ "$TOTAL" -eq 0 ]; then
  SUMMARY="Clew policy cache loaded: no active policies."
else
  SUMMARY="Clew policy cache loaded: $TOTAL policies ($BLOCK_COUNT block, $WARN_COUNT warn, $AUDIT_COUNT audit)."

  # List blocking rules for Claude's awareness
  BLOCK_RULES=$(echo "$POLICIES" | jq -r '.[] | select(.severity == "block") | "- [\(.type)] \(.pattern): \(.message)"')
  if [ -n "$BLOCK_RULES" ]; then
    SUMMARY="$SUMMARY\n\nBlocking rules:\n$BLOCK_RULES"
  fi
fi

# Return structured output for Claude context injection
printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}' \
  "$(echo -e "$SUMMARY" | sed 's/"/\\"/g' | tr '\n' ' ')"

exit 0
